I know how to test php output with PHPUnit library, using expectOutputString()
or expectOutputString()
. Now I need to be sure that output doesn't contain given string. I can do this using output buffering and searching for string inside but probably better way is to use expectOutputString()
with proper expression.
How should this expression be built?
You want to use a regex, and to do a negative match you have to use the lookahead assertion syntax. E.g. to test that the output does not contain "hello":
class OutputRegexTest extends PHPUnit_Framework_TestCase
{
private $regex='/^((?!Hello).)*$/s';
public function testExpectNoHelloAtFrontFails()
{
$this->expectOutputRegex($this->regex);
echo "Hello World!\nAnother sentence\nAnd more!";
}
public function testExpectNoHelloInMiddleFails()
{
$this->expectOutputRegex($this->regex);
echo "This is Hello World!\nAnother sentence\nAnd more!";
}
public function testExpectNoHelloAtEndFails()
{
$this->expectOutputRegex($this->regex);
echo "A final Hello";
}
public function testExpectNoHello()
{
$this->expectOutputRegex($this->regex);
echo "What a strange world!\nAnother sentence\nAnd more!";
}
}
Gives this output:
$ phpunit testOutputRegex.php
PHPUnit 3.6.12 by Sebastian Bergmann.
FFF.
Time: 0 seconds, Memory: 4.25Mb
There were 3 failures:
1) OutputRegexTest::testExpectNoHelloAtFrontFails
Failed asserting that 'Hello World!
Another sentence
And more!' matches PCRE pattern "/^((?!Hello).)*$/s".
2) OutputRegexTest::testExpectNoHelloInMiddleFails
Failed asserting that 'This is Hello World!
Another sentence
And more!' matches PCRE pattern "/^((?!Hello).)*$/s".
3) OutputRegexTest::testExpectNoHelloAtEndFails
Failed asserting that 'A final Hello' matches PCRE pattern "/^((?!Hello).)*$/s".
FAILURES!
Tests: 4, Assertions: 4, Failures: 3.
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