我正在尝试模拟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()
的作用?
答案 0 :(得分:2)
您可以使用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
函数到底能起到什么作用以及为什么您的方法行不通的问题……我不确定。