我正在尝试模拟 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 Expectation failed for method name is equal to when invoked zero or more times Parameter 0 for invocation Doctrine\ORM\EntityRepository::findOneBy(Array (...), null) does not match expected value. Failed asserting that two arrays are equal. --- Expected +++ Actual @@ @@ Array ( - 'id' => 50 + 'id' => 5000 )
删除上面两行中的任何一行即可消除该错误。我在这里做错了什么?我是否完全误解了 with()
的作用?
最佳答案
您可以使用withConsecutive
和willReturnOnConsecutiveCall
将多个with和return放入同一个函数中。我不太确定当你像你一样写它时会发生什么。
你的代码看起来像这样:
$this->vacancyRepositoryMock->method('findOneBy')->expects($this->exactly(2))
->withConsecutive([['id' => 5000]],[['id' => 50]]) //array in array is on purpose
->willReturnOnConsecutiveCalls(null, $myVacancy);
至于你关于 with
函数到底做什么以及为什么你的方法不起作用的问题......我不确定。
关于php - incallingMocker::with() 实际上做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58817472/