为什么先进行异常断言然后进行调用呢?
// 检查 $type 参数
public function testGetWeatherWithInvalidType()
{
$w = new Weather('mock-key');
// 断言会抛出此异常类
$this->expectException(InvalidArgumentException::class);
// 这里先进行了异常信息的断言, 然后 才调用的 getWeather()
// 断言异常消息为 'Invalid type value(base/all): foo'
$this->expectExceptionMessage('Invalid type value(base/all): foo');
$w->getWeather('深圳', 'foo');
$this->fail('Faild to assert getWeather throw exception with invalid argument.');
}
关于 LearnKu
因为异常发生时代码就终止往下运行了,所以你需要事先告诉测试框架"下面的代码可能会发生异常,请帮忙检查是否为我断言的样子”,测试框架就会进行 try catch 操作啦。