我看到很多关于如何使用 PHPUnit 来测试是否为方法抛出异常的答案 - 这很好,很好。
对于这段代码,我知道@expectsException将允许我测试 try{} 块和 thing1()。如何测试thing2()
位和thing3()
位?
try {
thing1();
}
catch (Exception $e) {
thing2();
thing3();
}
这是我现在失败的内容:
function myTest() {
$prophecy = $this->prophesize(Exception::CLASS);
$my_exception = $prophecy->reveal();
// more testing stuff
...
}
PHPUnit 将reveal()
调用视为意外异常,并在"更多测试内容"之前退出。
注释
expectedException
用于声明,该测试将以未处理的异常完成。
在您的情况下,正如 Ancy C 所注意到的,thing1()
必须抛出任何异常,然后调用thing2()
和thing3()
,您可以测试它们。
编辑:
一定在某处有错误。这对我来说非常有效
<?php
class Stack
{
public function testMe()
{
try {
$this->thing1();
} catch (Exception $e) {
return $this->thing2();
}
}
private function thing1()
{
throw new Exception();
}
private function thing2()
{
return 2;
}
}
和测试类:
class StackTest extends TestCase
{
public function test()
{
$stack = new Stack();
$result = $stack->testMe();
self::assertEquals(2, $result);
}
}
结果:
PHPUnit 5.5.4 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 20 ms, Memory: 4.00MB
OK (1 test, 1 assertion)