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
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
}
}
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);
}
What worked for me was modifying my phpunit.xml to have
<phpunit
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
strict="true"
>
</phpunit>
The key was to use strict="true"
to get the warnings to result in a failed test.
Using Netsilik/BaseTestCase (MIT License) you can test directly for triggered Errors/Warnings, without converting them to Exceptions:
composer require netsilik/base-test-case
Testing for an E_USER_NOTICE
:
<?php
namespace Tests;
class MyTestCase extends \Netsilik\Testing\BaseTestCase
{
/**
* {@inheritDoc}
*/
public function __construct($name = null, array $data = [], $dataName = '')
{
parent::__construct($name, $data, $dataName);
$this->_convertNoticesToExceptions = false;
$this->_convertWarningsToExceptions = false;
$this->_convertErrorsToExceptions = true;
}
public function test_whenNoticeTriggered_weCanTestForIt()
{
$foo = new Foo();
$foo->bar();
self::assertErrorTriggered(E_USER_NOTICE, 'The warning string');
}
}
Hope this helps someone in the future.
Make SomeClass throw an error when input is invalid and tell phpUnit to expect an error.
One method is this:
class ExceptionTest extends PHPUnit_Framework_TestCase
{
public function testLoadValueWithNull()
{
$o = new SomeClass();
$this->setExpectedException('InvalidArgumentException');
$this->assertInstanceOf('InvalidArgumentException', $o::loadValue(null));
}
}
See documentation for more methods.
You can also write a phpunit.xml file (on your tests dir) with this:
<phpunit
convertErrorsToExceptions="true"
convertNoticesToExceptions="false"
stopOnFailure="false">
</phpunit>