简体   繁体   中英

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?

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.

I don't know the whole your story, but I assume that your first mistake was that you did not create a testing database.
So, that would be the first step - in addition to your databaseName (whatever the name) create a databaseName_test.
There are some other steps to do - in your ,env file change the name of the databaseName to databaseName_testing - but only while you're doing your testing (and then immediately rollback to your original databaseName).
Yet, the problem can still persist (PHP Unit is not a perfect tool, just like PHP), and here is the hack that can help.
Instead of:

    $this->assertEquals(3, $difference);

write:

    $this->assertEquals(11935, $difference); //the number is specific for your case

Yep, it's stupid, but it should work...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM