Search code examples
laravelunit-testingphpunitlaravel-testing

How to test array contains only objects with PHPUnit?


I'm looking for solution to test an array of objects with PHPUnit in my Laravel project.

This is my haystack array:

[
    [
        "id" => 10,
        "name" => "Ten"
    ],
    [
        "id" => 5,
        "name" => "Five"
    ]
]

And this is the needles array:

[
    [
        "id" => 5,
        "name" => "Five"
    ],
    [
        "id" => 10,
        "name" => "Ten"
    ]
]

The order of objects doesn't matter, also keys of objects doesn't matter. The only matter is we have two objects and all objects has exactly same keys and exactly same values.

What is the correct solution for this?


Solution

  • You can do this using the assertContainsEquals method like this:

    $haystack = [
        [
            'id' => 10,
            'name' => 'Ten'
        ],
        [
            'id' => 5,
            'name' => 'Five'
        ]
    ];
    
    $needles = [
        [
            'name' => 'Five',
            'id' => 5
        ],
        [
            'id' => 10,
            'name' => 'Ten'
        ]
    ];
    
    foreach ($needles as $needle) {
        $this->assertContainsEquals($needle, $haystack);
    }
    

    You could also a create your own assert method if you intend to perform the assertion more often:

    public function assertContainsEqualsAll(array $needles, array $haystack): void
    {
        foreach ($needles as $needle) {
            $this->assertContainsEquals($needle, $haystack);
        }
    }