mercredi 4 mai 2016

Why does the order of Mockery mocks of Eloquent models matter for the runtime execution of the tests?

I am working on a Laravel app and am using Eloquent models.

Additionally, I am trying to write good unit tests. To this end, my code is structured in a way that is as cohesive as is manageable; however, at some point I have to mock these models.

This is mostly going pretty well, but I have encountered a strange situation that I do not understand (though I'm sure there is a logical explanation for it).

This is what my test looks like:

$thing = Mockery::mock('Things\Thing');
$thing_2 = Mockery::mock('Things\Thing');

$thing->shouldReceive('all')->once()->andReturn(collect([$thing_2]));
$thing_2->shouldReceive('getAttribute')->with('name')->once()->andReturn('Thing 2');

If I execute the tests using these mocks, everything works just fine; however, if I switch the first two lines:

$thing_2 = Mockery::mock('Things\Thing');
$thing = Mockery::mock('Things\Thing');


$thing->shouldReceive('all')->once()->andReturn(collect([$thing_2]));
$thing_2->shouldReceive('getAttribute')->with('name')->once()->andReturn('Thing 2');

Then I get an exception:

BadMethodCallException: Static method Mockery_1_Things_Thing::all() does not exist on this mock object

I'm sure there is some simple explanation for this, but I am pretty new to PHP and the Laravel framework, and I'm coming up dry with my googlin'.

Any help is appreciated!

Aucun commentaire:

Enregistrer un commentaire