【问题标题】:Mocking find($collection) in repository pattern in Laravel with Mockery使用 Mockery 在 Laravel 的存储库模式中模拟 find($collection)
【发布时间】:2019-10-24 19:14:23
【问题描述】:

我正在做单元测试,我的存储库有这个方法:

/**
 * @param int|Collection $id
 * @return MyModel|Collection|null
 */
 public function find($id);

我试过这个:

$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.

测试立即失败,我认为这是因为shouldReceive 期望语句和实际find 语句中的2 个集合是不同的对象。

如果我想模拟$this->ticket_repo->find($ids)的行为,我该怎么办?

或者更确切地说,如果有更好的方法来设计可测试的算法,它会怎样?因为我希望将所有要查找的 id 放在一个数组中,并构造成一个 SQL 选择查询,而不是几百个单独的查询,以提高性能。

也在这里问:https://laracasts.com/discuss/channels/testing/mocking-findcollection-in-repository-pattern-in-laravel-with-mockery#

【问题讨论】:

    标签: php laravel phpunit mockery


    【解决方案1】:

    你必须模拟一个具体的类而不是接口。由于您没有提供我只是猜测的名称:

    $mock = Mockery::mock(TicketRepo::class);
    $this->app->swap('PackageRepo', $mock);
    

    所以现在每当有人通过接口名称请求实例时,他们都会得到模拟。

    【讨论】:

      猜你喜欢
      • 2014-11-05
      • 2015-06-15
      • 2016-08-17
      • 2015-03-27
      • 2022-01-04
      • 2014-03-15
      • 2014-01-09
      • 2014-12-04
      • 2018-03-26
      相关资源
      最近更新 更多