您想使用正则表达式,并且要进行否定匹配,您必须使用先行断言语法。例如测试输出不包含“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!";
}
}
Run Code Online (Sandbox Code Playgroud)
给出这个输出:
$ 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.
Run Code Online (Sandbox Code Playgroud)
这很简单。测试该字符串不包含其他字符串:
2020 年,PHPUnit 9.x 以上还有另一种简洁的方法:
$this->assertStringNotContainsString(needle, haystack);
Run Code Online (Sandbox Code Playgroud)
请参阅 PHPUnit断言文档。并非所有可用的断言都记录在文档中。
找到这些的好方法是从 PHPUnit 测试类中dd($this)运行 Laravel(或var_dump($this)纯 PHP)并滚动浏览输出methods部分。在那里您可以看到可用的断言,包括未记录的断言。
更详细、更灵活,不仅适用于字符串,还具有不同的断言。
$string='just some string';
$this->assertThat($string, $this->logicalNot($this->stringContains('script')));
// Assertion is passed.
Run Code Online (Sandbox Code Playgroud)
我用它来检查表单字段的清理是否正常。
在 PHPUnit 测试中,我建立了一个测试数组,<script>其中包含要清理的标签。将其传递给正在测试的消毒方法。序列化清理结果(以避免弄乱数组的断言,并且在var_dump“序列化结果”时更方便我的眼睛)。
然后在断言stringContains中应用该方法assertThat,如上所示并享受:)
| 归档时间: |
|
| 查看次数: |
2821 次 |
| 最近记录: |