Search code examples
phptestingphpunittddassertions

PHPUnit test - Failed asserting that actual size 11935 matches expected size 3


I'm brand new to phpunit and attempting to write a test that asserts that three notes were created, but I'm getting all of the notes from the DB.

    /** @test */
    public function it_gets_notes()
    {
        $address = Address::first();
        $notes = factory(AddressNote::class, 3)->create(['address_id' 
        => $address->id]);
        $found = $this->notesClass->getData(['address_id' => $address-
        >id]);
        $this->assertCount(3, $found);
    }
}

The Address and AddressNote models are working properly. I think I'm most confused about the getData method, which I know I need for my code coverage. Anyone see what I'm missing that would generate the error in the title?


Solution

  • If you need to check the difference after running your create method, then save $found before and after adding them, and the subtraction will be your number:

    public function it_gets_notes()
    {
        $address = Address::first();
        $found = $this->notesClass->getData(['address_id' => $address->id]);
        $notes = factory(AddressNote::class, 3)->create(['address_id' => $address->id]);
        $foundAfter = $this->notesClass->getData(['address_id' => $address->id]);
        $difference = count($foundAfter) - count($found);
        $this->assertEquals(3, $difference);
    }
    

    Note that you need to use assertEquals() with 3 and the difference now instead of assertCount(), since you're comparing numbers.