How to mock the same method in Prophecy so it returns different response in each of its calls

你。 提交于 2021-02-07 20:35:44

问题


In pure PHPUnit mocking I can do something like this:

$mock->expects($this->at(0))
    ->method('isReady')
    ->will($this->returnValue(false));

$mock->expects($this->at(1))
    ->method('isReady')
    ->will($this->returnValue(true));

I was not able to do the same thing using Prophecy. Is it possible?


回答1:


You can use:

$mock->isReady()->willReturn(false, true);

Apparently it's not documented (see https://gist.github.com/gquemener/292e7c5a4bbb72fd48a8).




回答2:


There is another documented way to do that. If you expect a different result on a second call, it means something has changed in between, and you probably used a setter to modify the object's state. This way you can tell your mock to return a specific result after calling a setter with specific argument.

$mock->isReady()->willReturn(false);

$mock->setIsReady(true)->will(function () {
    $this->isReady()->willReturn(true);
});

// OR

$mock->setIsReady(Argument::type('boolean'))->will(function ($args) {
    $this->isReady()->willReturn($args[0]);
});

More about it here https://github.com/phpspec/prophecy#method-prophecies-idempotency.



来源:https://stackoverflow.com/questions/32336511/how-to-mock-the-same-method-in-prophecy-so-it-returns-different-response-in-each

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!