我正在编写测试用例,这是我的一个问题.
所以说我正在测试一个简单的函数 someClass::loadValue($value)
正常的测试用例很简单,但假设在传入null或-1时,函数调用会生成一个PHP警告,这被认为是一个错误.
问题是,如何编写我的PHPUnit测试用例,以便在函数正常处理null/-1时成功,并在抛出PHP警告时失败?
谢谢,
Dav*_*ess 38
PHPUnit_Util_ErrorHandler::handleError() 根据错误代码抛出几种异常类型之一:
PHPUnit_Framework_Error_Notice对E_NOTICE,E_USER_NOTICE和E_STRICTPHPUnit_Framework_Error_Warning为E_WARNING和E_USER_WARNINGPHPUnit_Framework_Error 为所有其他人您可以像捕获任何其他异常一样捕获并期望这些.
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
function testNegativeNumberTriggersWarning() {
$fixture = new someClass;
$fixture->loadValue(-1);
}
Run Code Online (Sandbox Code Playgroud)
对我有用的是修改我的phpunit.xml
<phpunit
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
strict="true"
>
</phpunit>
Run Code Online (Sandbox Code Playgroud)
关键是用来strict="true"获取警告导致测试失败.
我会创建一个单独的案例来测试预期通知/警告的时间.
对于PHPUnit v6.0 +,这是最新的语法:
use PHPUnit\Framework\Error\Notice;
use PHPUnit\Framework\Error\Warning;
use PHPUnit\Framework\TestCase;
class YourShinyNoticeTest extends TestCase
{
public function test_it_emits_a_warning()
{
$this->expectException(Warning::class);
file_get_contents('/nonexistent_file'); // This will emit a PHP Warning, so test passes
}
public function test_it_emits_a_notice()
{
$this->expectException(Notice::class);
$now = new \DateTime();
$now->whatever; // Notice gets emitted here, so the test will pass
}
}
Run Code Online (Sandbox Code Playgroud)
小智 -2
当输入无效时让 SomeClass 抛出错误并告诉 phpUnit 预计会出现错误。
一种方法是这样的:
class ExceptionTest extends PHPUnit_Framework_TestCase
{
public function testLoadValueWithNull()
{
$o = new SomeClass();
$this->setExpectedException('InvalidArgumentException');
$this->assertInstanceOf('InvalidArgumentException', $o::loadValue(null));
}
}
Run Code Online (Sandbox Code Playgroud)
更多方法请参阅文档。
| 归档时间: |
|
| 查看次数: |
10981 次 |
| 最近记录: |