I am writing test cases and here is a question I have.
So say I am testing a simple function someClass::loadValue($value)
The normal test case is easy, but assume when passing in null or -1 the function call generates a PHP Warning, which is considered a bug.
The question is, how do I write my PHPUnit test case so that it succeeds when the functions handles null/-1 gracefully, and fail when there is a PHP Warning thrown?
Unit testing is a software testing process in which code blocks are checked to see whether the produced result matches the expectations. The units are tested by writing a unique test case. The unit test is generally automatic but could be implemented manually.
PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks. PHPUnit 9 is the current stable version. PHPUnit 10 is currently in development.
One of the most time-consuming parts of writing tests is writing the code to set the world up in a known state and then return it to its original state when the test is complete. This known state is called the fixture of the test.
PHPUnit_Util_ErrorHandler::handleError()
throws one of several exception types based on the error code:
PHPUnit_Framework_Error_Notice
for E_NOTICE
, E_USER_NOTICE
, and E_STRICT
PHPUnit_Framework_Error_Warning
for E_WARNING
and E_USER_WARNING
PHPUnit_Framework_Error
for all othersYou can catch and expect these as you would any other exception.
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
function testNegativeNumberTriggersWarning() {
$fixture = new someClass;
$fixture->loadValue(-1);
}
I would create a separate case to test when the notice/warning is expected.
For PHPUnit v6.0+ this is the up to date syntax:
use PHPUnit\Framework\Error\Notice;
use PHPUnit\Framework\Error\Warning;
use PHPUnit\Framework\TestCase;
class YourShinyNoticeTest extends TestCase
{
public function test_it_emits_a_warning()
{
$this->expectException(Warning::class);
file_get_contents('/nonexistent_file'); // This will emit a PHP Warning, so test passes
}
public function test_it_emits_a_notice()
{
$this->expectException(Notice::class);
$now = new \DateTime();
$now->whatever; // Notice gets emitted here, so the test will pass
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With