dragon321723 2016-10-09 01:57
浏览 109
已采纳

PHPUnit在对象创建中测试断言

When I run phpunit I get:

1) FooTests::testException assert(): Assertion "false" failed

I would like to expect the assert in the case I have.

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');
    }

}
  • 写回答

1条回答 默认 最新

  • duanrao3371 2016-10-09 07:48
    关注

    You can achieve in one of the following manner:

    1) Catch the PHPUnit warning exception

    PHP emit a warning for each failed assertion, so PHPUnit raise an exception of the type PHPUnit_Framework_Error_Warning. As described in the doc:

    By default, PHPUnit converts PHP errors, warnings, and notices that are triggered during the execution of a test to an exception.

    [..]

    PHPUnit_Framework_Error_Notice and PHPUnit_Framework_Error_Warning represent PHP notices and warnings, respectively.

    So you can simply catch in the following manner:

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

    2) Using a callback on failed assertion

    You could do something more clear using the assert_options, using as callback a custom exception and handle it as example:

    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) Change the behaviour of the failing exception (only from PHP7)

    If you are using PHP7 you could implement this last behaviour with a new settings called assert.exception:

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

    Hope this help

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)