[英]Mocking find($collection) in repository pattern in Laravel with Mockery
I'm doing unit testing and my repository has this method: 我正在进行单元测试,我的存储库有这个方法:
/**
* @param int|Collection $id
* @return MyModel|Collection|null
*/
public function find($id);
I tried this: 我试过这个:
$this->package_repo = Mockery::mock(PackageRepositoryInterface::class);
$this->app->instance('Package', $this->package_repo);
// ...
$this->ticket_repo->shouldReceive("find")->with(collect([]))->andReturn(/*...*/);
//...
echo $this->ticket_repo->find(collect([])); // Failed here.
The test immediately failed, and I think it's because the 2 collections in the shouldReceive
expectation statement and the actual find
statement are distinct objects. 测试立即失败,我认为这是因为
shouldReceive
expectation语句中的2个集合和实际的find
语句是不同的对象。
If I want to mock the behavior of $this->ticket_repo->find($ids)
, what should I do? 如果我想模仿
$this->ticket_repo->find($ids)
,我该怎么办?
Or rather, if there is a better way to design a testable algorithm, how would it be? 或者更确切地说,如果有更好的方法来设计可测试算法,它会是怎样的? Because I would like to have all the ids to I want to find be in an array, and be constructed into a single SQL select query, instead of a few hundred separate ones, for performance purposes.
因为我希望将所有ID都放在数组中,并将其构建为单个SQL select查询,而不是几百个单独的查询,以实现性能目的。
Also asked here: https://laracasts.com/discuss/channels/testing/mocking-findcollection-in-repository-pattern-in-laravel-with-mockery# 此处还询问: https : //laracasts.com/discuss/channels/testing/mocking-findcollection-in-repository-pattern-in-laravel-with-mockery#
You have to mock a concrete class and not the interface. 你必须模拟一个具体的类而不是界面。 Since you haven't provided the name I'm just guessing:
既然你没有提供我只是猜测的名字:
$mock = Mockery::mock(TicketRepo::class);
$this->app->swap('PackageRepo', $mock);
So now whenever someone asks for an instance by the Interface name they'll get the mock. 所以现在每当有人通过接口名称请求实例时,他们都会得到模拟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.