2

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
  • the behaviour is due to an exception rised from phpunit of the type: PHPUnit_Framework_Error_Warning which version of php are you using? Commented Oct 9, 2016 at 7:27

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Matteo, that answer is perfect. Option three worked like a charm!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.