【发布时间】:2019-09-06 09:35:55
【问题描述】:
当我测试一个使用 expectExceptionMessage('exception message') 引发异常的构造函数时,测试失败并且实际消息文本以“Class 'namespace\Class_Name'”为前缀。
它还指出抛出了一个 Error 类型的异常,而不是预期的 Exception 类型。
我是否错误地抛出了我的异常?
通过省略expectExceptionMessage 函数并将代码包含在try catch 语句中,我能够使测试通过。 这对我来说没有意义。
使用注释
/**
* @expectedException Exception
* @expectedExceptionMessage no_file.json not found
*/
也没有解决问题。
PHPUnit测试代码:
public function testNonExistingFileInConstructor() {
$this->expectException( 'Exception' );
$this->expectExceptionMessage( 'no_file.json not found');
new Json_File('no_file.json');
}
抛出异常的代码:
public function __construct( $path_to_file ) {
$json_file = file_get_contents( $path_to_file );
if( false === $json_file ) {
throw new Exception( $json_file . ' not found', 500 );
}
$data = json_decode( $json_file, true );
if ( is_null( $data) ) {
throw new Exception( 'invalid json in ' . $json_file, 600 );
}
$this->data = $data;
}
【问题讨论】: