PHPUnit没有捕获预期的异常

时间:2010-11-11 20:34:30

标签: php unit-testing exception phpunit

我有一组测试,我想测试我的类在正确的时间抛出异常。在示例中,我的类使用__get()魔术方法,因此我需要测试在检索到无效属性时抛出异常:

function testExceptionThrownWhenGettingInvalidProperty() {
  $obj = new MyClass();
  $this->setExpectedException("Property qwerty does not exist");
  $qwerty = $obj->qwerty;
}

该类会抛出错误,但不会只是获取传递,而是捕获异常!

There was 1 error:

1) QueryTest::testExceptionThrownWhenGettingInvalidProperty
Exception: Property qwerty does not exist

之前我使用的是SimpleTest,$this->expectException(new Exception("Property qwerty does not exist"));工作正常。我知道还有其他方法(@expectedException和try-catch),但是这个方法应该可以工作,看起来更清晰。我有什么想法可以让它发挥作用吗?

2 个答案:

答案 0 :(得分:13)

它没有在异常中查找文本,它正在寻找异常类的名称...... Docs

$this->setExpectedException('Exception');

当您使用SPL Exceptions或自定义异常类...

时,它非常方便

答案 1 :(得分:13)

添加到ircmaxell的答案,实际上有一种更简单的方法:

/**
 * @expectedException MyExceptionClass
 * @expectedExceptionMessage Array too small
 */
public function testSomething()
{
}

@expectedException期望的异常的类名,@expectedExceptionMessage是期​​望的异常消息的子字符串(这是正确的,您不必拥有整个消息)。< / p>

如果您不想使用docblock注释,那么这两个注释实际上都可用作测试用例的方法。

相关问题