我正在尝试模拟Doctrine存储库,并根据提供给findOneBy()方法的内容,使模拟存储库返回不同的结果。设置测试时,我使用以下代码:
$this->vacancyRepositoryMock->method('findOneBy')->with(['id' => 5000])->willReturn(null);
$this->vacancyRepositoryMock->method('findOneBy')->with(['id' => 50])->willReturn($myVacancy);
不幸的是,这导致我得到以下输出:
1)Tests \ AppBundle \ Service \ VacancyServiceTest :: testAddName期望
方法名称等于调用时失败
零次或多次调用参数0
Doctrine \ ORM \ EntityRepository :: findOneBy(Array(...),null)不
匹配期望值。无法断言两个数组相等。
---预期
+++实际@@ @@数组(
-'id'=> 50
+'id'=> 5000)
删除上面两行中的任何一条都可以消除该错误。我在这里做错了什么?我完全误解了
with()
是什么吗? 最佳答案
您可以使用withConsecutive
和willReturnOnConsecutiveCall
将多个withs和return放入同一函数中。我不确定当您像以前那样编写时会发生什么。
您的代码如下所示:
$this->vacancyRepositoryMock->method('findOneBy')->expects($this->exactly(2))
->withConsecutive([['id' => 5000]],[['id' => 50]]) //array in array is on purpose
->willReturnOnConsecutiveCalls(null, $myVacancy);
至于您对
with
函数到底能做什么以及为什么您的方式不起作用的问题……我不确定。