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 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低