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