fbmfbm's avatar

Events not fired in phpunit test ?

Hi all,

I'm looking to unit test with phpunit my event's process that record logs in database but facing some trouble :

In unit test, no event seam to be fired and so my log test table stay empty. I know that in prod en dev it's working because as event is well fired and on event a new record is created in db. I can test other db recording process without problem, but only event action seam to not be fired and my log actions table stay empty.... All other tables are well populate.

Is something special with event process to unit test with phpunit or doese use a particular process ??

I'm using laravel 5.4 with phpunit from vendor/bin/phpunit as 5.7.20.

Thank's for your help.

fbm

0 likes
3 replies
fbmfbm's avatar

Thank's tykus !

i'm testing then fonctionnality that get rise to the event AND the eventitself. But your link seam to be verry helpfull. i'll se it one more time to best undersand unit testing.

fbm

fbmfbm's avatar

well... i cant get event fired .

That's my code for assertTesting

public function testPerimetersDatabaseExist() { $perim = factory(Perimeter::class)->create([ 'opal_code' => '12345AA' ]);

    Event::shouldReceive('fire')->with(new PerimeterCreated($perim))->once();

    $this->assertDatabaseHas('perimeters',[ 'opal_code' => '12345AA']);
}

And this is the event fired method in controller :

event(new PerimeterCreated($newPerimeter));

Where PerimeterCreated() is the event i want to look at.

phpunit return allway this error :

  1. Tests\Unit\PerimTest::testPerimetersDatabaseExist Mockery\Exception\InvalidCountException: Method fire(object(App\Events\PerimeterCreated)) from Mockery_0_Illuminate_Events_Dispatcher should be called exactly 1 times but called 0 times.

Please or to participate in this conversation.