问题描述
我需要测试我编写的某些代码在多次调用另一个类上的方法时的行为方式,其中一次调用会导致抛出异常.
I need to test how some code I wrote will behave when it calls a method on another class multiple times, where one of the calls will cause an exception to be thrown.
我正在使用 Mockery 来模拟可能引发异常的类.
I am using Mockery to mock the class that may throw an exception.
所以在我的例子中,该方法将被调用三次,我需要它在第二次抛出异常.
So in my case, the method will be called three times and I need it throw an exception on the second time.
这是我的意图的例子,但它不起作用.
This is example of my intention but it doesn't work.
$mock = \Mockery::mock();
$mock->shouldReceive('fetch')
->andReturnUsing(
function () {return true;},
function () use ($e) {throw new \Exception();},
function () {return false;}
);
我从 Asserting that mock抛出异常 · 问题 #308 · 嘲弄/嘲弄.
然而,在实践中,以这种方式抛出异常会导致 Mockery 捕获异常并抛出自己的 BadMethodCall
异常.
However, in practice, throwing an exception this way causes Mockery to catch the exception and throw its own BadMethodCall
exception.
推荐答案
我在 Mockery Github 问题中找到了答案,用返回和抛出模拟多个方法调用.
I found the answer amongst the Mockery Github Issues, Mock multiple method call with return and throw.
$mock = \Mockery::mock();
$mock->shouldReceive('fetch')
->andReturnUsing(
function () use () {
static $counter = 0;
switch ($counter++) {
case 0:
return true;
break;
case 1:
throw new \Exception();
break;
default:
return false;
break;
}
}
);
对于那些正在寻找使用 PHPUnit 的解决方案的人...
For those looking for a solution using PHPUnit...
$mockHydrator = $this->createMock(MyObject::class);
$mockHydrator->method('fetch')
->will(
$this->onConsecutiveCalls(
true,
$this->throwException($e),
false
)
);
这是我觉得 PHPUnit mocks 提供比 Mockery 更好的界面的一种情况.
This is one case where I feel PHPUnit mocks provides a better interface than Mockery.
这篇关于如何使用 Mockery 在第 N 次调用模拟方法时抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!