【问题标题】:PHPunit ignores Exceptions in the setup methodPHPunit 忽略 setup 方法中的异常
【发布时间】:2011-09-30 07:39:20
【问题描述】:

我注意到 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?

【问题讨论】:

  • 这对您有帮助吗?还有问题吗?

标签: php exception installation phpunit


【解决方案1】:

这里抛出异常不是正确的做法,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

【讨论】:

  • 是的,我知道,这只是一个示例,那里调用了一些 dataBaseConnection 代码,可能会在连接失败时引发异常。
【解决方案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.

您的代码可运行:

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

}

【讨论】:

  • 哎呀,对于迟到的反应感到非常抱歉。无论如何,它还没有完全解决,但是我们发现问题不在于 phpunit,而在于其他东西(不太确定究竟是什么)。无论如何,非常感谢您的时间和帮助!
猜你喜欢
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
  • 2013-10-02
  • 1970-01-01
相关资源
最近更新 更多