【问题标题】:PHPUnit test assert in object create对象创建中的 PHPUnit 测试断言
【发布时间】:2017-02-17 17:58:53
【问题描述】:

当我运行 phpunit 时,我得到:

1) FooTests::testException assert(): 断言“假”失败

我希望在我的情况下得到断言。

class FooTests extends WP_UnitTestCase {

  protected $foo;

    public function setUp() {
        parent::setUp();
        $this->foo = new Foo();
    }

    function testException() {
        // I'd like to expect an assert in the class foo so the test should not fail.  
        $this->foo->test();
    }
}

class Foo {
    public function __construct(){
    }

    public function __destruct(){}


    public function test(){
      assert('false');
    }

}

【问题讨论】:

  • 该行为是由于以下类型的 phpunit 引发的异常:PHPUnit_Framework_Error_Warning您使用的是哪个版本的 php?

标签: php unit-testing phpunit


【解决方案1】:

您可以通过以下方式之一实现:

1) 捕捉 PHPUnit 警告异常

PHP 会为每个失败的断言发出警告,因此 PHPUnit 会引发异常 类型为PHPUnit_Framework_Error_Warning。如doc中所述:

默认情况下,PHPUnit 会转换 PHP 错误、警告和通知 在执行异常测试期间触发。

[..]

PHPUnit_Framework_Error_NoticePHPUnit_Framework_Error_Warning 分别代表 PHP 通知和警告。

所以你可以通过以下方式简单地捕捉:

public function testException() {
    $this->expectException(\PHPUnit_Framework_Error_Warning::class);
    $this->foo->test();
}

2) 对失败的断言使用回调

您可以使用assert_options 做一些更清楚的事情,使用自定义异常作为回调并作为示例处理它:

public function test_using_assert_options_PHP5()
{
    $fnc = function() {
        throw new \Exception('assertion failed', 500);
    };

    $this->expectException(\Exception::class);
    $this->expectExceptionCode(500);
    $this->expectExceptionMessage('assertion failed');

    assert_options(ASSERT_CALLBACK, $fnc);
    $this->foo->test();
}

3) 更改失败异常的行为(仅限 PHP7)

如果您使用的是 PHP7,您可以使用名为 assert.exception 的新设置来实现最后一个行为:

public function test_using_assert_options_PHP7()
{
    $this->expectException(\AssertionError::class);
    assert_options(ASSERT_EXCEPTION, 1);
    $this->foo->test();
}

希望有帮助

【讨论】:

  • 谢谢你,Matteo,这个答案是完美的。选项三就像一个魅力!
猜你喜欢
  • 2013-12-06
  • 1970-01-01
  • 2021-04-20
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多