PHPUnit tests succeed failing
November 7, 2014
Asserting that a test should fail in PHPUnit.
The problem
In the process of developing the function mocker I need to verify that a certain test will fail.
Take this one for example:
/**
* @test
* it should allow setting times the mocked function should be called and fail when called less times
*/
function it_should_allow_setting_times_the_mocked_function_should_be_called_and_fail_when_called_less_times() {
FunctionMocker::mock( __NAMESPACE__ . '\someFunction' )->shouldBeCalledTimes( 3 );
someFunction();
someFunction();
// explicit call, should not happen
MockCallLogger::tearDown();
}
I'm expecting someFunction
to be called 3 times and it's instead called just 2 times, the mock object should assert the failure of the test and I want to verify it. Since the tool is meant to be used in conjunction with PHPUnit the expected failure sent by the subject under test will make the test fail Not the expected result.
A quick solution
Using PHPUnit annotations solving the problems is a one liner:
/**
* @test
* it should allow setting times the mocked function should be called and fail when called less times
* @expectedException \PHPUnit_Framework_AssertionFailedError
*/
function it_should_allow_setting_times_the_mocked_function_should_be_called_and_fail_when_called_less_times() {
FunctionMocker::mock( __NAMESPACE__ . '\someFunction' )->shouldBeCalledTimes( 3 );
someFunction();
someFunction();
// explicit call, should not happen
MockCallLogger::tearDown();
}
I've added the @expectedException
annotation expecting just the type of exception the PHPUnit_Framework_Assert::fail
method will raise; that's the method I'm using to make the mock expectations fail.