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

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

报告相同问题?

悬赏问题

  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复