Am using PHPUnit for unit testing my functions when ever any warning comes in code the test script will not be executed for that functions, can anyone tell me how to ignore
As Juhana commented you should first of all fix your code where the warning(s) appear. It's a sign that the code is not working properly / strictly.
By default, PHPUnit converts PHP errors, warnings, and notices that are triggered during the execution of a test to an exception.
See Testing PHP Errors which has more information how to test for your warnings (and how to ignore warnings in sub-routines you call in tests).
To disable the default behaviour, you can tell PHPUnit to do so in your tests, e.g. within the setUp
of your test or the test itself by setting a static variable in the global namespace:
# Warning:
PHPUnit_Framework_Error_Warning::$enabled = FALSE;
# notice, strict:
PHPUnit_Framework_Error_Notice::$enabled = FALSE;
Another option to change the default behaviour is to configure the testrunner with an XML file with the following settings:
<phpunit convertErrorsToExceptions="false"
convertNoticesToExceptions="false"
convertWarningsToExceptions="false">
</phpunit>
These three options are not available as command-line switches.
See as well the related question: test the return value of a method that triggers an error with PHPUnit.
The documentented strategy to do this at a per-test level is to use the @
error suppression operator when your test calls the function that would trigger a warning or notice.
The following code is the example from the PHPUnit documentation:
<?php
class ErrorSuppressionTest extends PHPUnit_Framework_TestCase
{
public function testFileWriting() {
$writer = new FileWriter;
$this->assertFalse(@$writer->write('/is-not-writeable/file', 'stuff'));
}
}
class FileWriter
{
public function write($file, $content) {
$file = fopen($file, 'w');
if($file == false) {
return false;
}
// ...
}
}
You should not ignore warnings, they are there for a reason. Having said that, warnings and notices are not intended to be fatal (they would have been an error if they were intended to be fatal).
Instead of ignoring the warning, you should test for it in a unit test. You can do so by using Netsilik/BaseTestCase (MIT License). With this extension to PHPUnit, 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.