我注意到PHPUnit忽略了在setUp()
方法中抛出的异常,即使在setup函数抛出异常时也只是简单地运行测试。
在下面的代码中,异常将被忽略,它下面的代码将不会运行,并且test_method
将失败,因为它使用了未定义的变量。
protected $a;
public function setUp() {
parent:setUp();
throw new Exception(); // setup now exits silently.
$this->a = new A(); // will never run
}
public function testA() {
$this->assertTrue($this->a->something()); // will exit tests with PHP error, because $this->a === null
}
我正在使用phpunit.xml配置文件通过CLI运行phpunit。
有没有人知道一种方法,使PHPunit报告异常,然后停止执行testCase?
抛出异常不是正确的方法,在PHPUnit中有一个特殊的方法:
<?php
class DatabaseTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!extension_loaded('mysqli')) {
$this->markTestSkipped(
'The MySQLi extension is not available.'
);
}
}
public function testConnection()
{
// ...
}
}
?>
http://www.phpunit.de/manual/current/en/incomplete-and-skipped-tests.html incomplete-and-skipped-tests.skipping-tests
不能repoduce
运行该脚本(下面是完整的示例)会产生一个错误输出,其中包含异常。
我假设你有一个问题在其他地方或可能是旧的phpunit版本?即使这样,我也不知道这段代码有任何变化。
你可能也从主干运行phpunit ?("3.6")在这种情况下,"Exception"
类的处理本身发生了变化,现在不能测试这种情况,但如果这适用于你尝试使用InvalidArgumentException()(只是为了测试),看看这是否改变了事情。
phpunit test.php
PHPUnit 3.5.13 by Sebastian Bergmann.
E
Time: 0 seconds, Memory: 3.00Mb
There was 1 error:
1) FooTest::testA
Exception: hi
/home/.../test.php:10
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
你的代码可运行:
<?php
class FooTest extends PHPUnit_Framework_TestCase {
protected $a;
public function setUp(){
parent::setUp();
throw new Exception('hi'); //setup now exits silently.
$this->a = new A(); //will never run
}
public function testA(){
$this->assertTrue($this->a->something()); //will exit tests with PHP error, because $this->a === null
}
}