Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch PHP Warning in PHPUnit

Tags:

phpunit

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?

like image 225
boots Avatar asked Feb 19 '11 22:02

boots


People also ask

What is unit test PHP?

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.

What is PHPUnit used for?

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.

What are PHPUnit fixtures?

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.


2 Answers

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 others

You can catch and expect these as you would any other exception.

/**
 * @expectedException PHPUnit_Framework_Error_Warning
 */
function testNegativeNumberTriggersWarning() {
    $fixture = new someClass;
    $fixture->loadValue(-1);
}
like image 119
David Harkness Avatar answered Nov 13 '22 01:11

David Harkness


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
    }
}
like image 12
Attila Fulop Avatar answered Nov 13 '22 00:11

Attila Fulop