PHPunit 忽略设置方法中的异常

Pim*_*ger 5 php installation phpunit exception

我注意到 PHPUnit 会忽略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
}
Run Code Online (Sandbox Code Playgroud)

我通过 CLI 使用 phpunit.xml 配置文件运行 phpunit。

有谁知道如何让 PHPunit 报告异常,然后停止 testCase 的执行?

edo*_*ian 2

无法重现

运行脚本(下面的完整示例)会产生带有异常的错误输出。

我假设你在其他地方有问题或者可能是旧的 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.
Run Code Online (Sandbox Code Playgroud)

您的代码可运行:

<?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
    }

}
Run Code Online (Sandbox Code Playgroud)