如果找到正则表达式文本,PHPUnit assertTrue?

时间:2013-09-26 23:31:38

标签: php phpunit assert

我正在使用PHPUnit并尝试检查页面上是否存在文本。 assertRegExp工作但使用if语句我收到错误Failed asserting that null is true.

我知道$ test返回null,但我不知道如果文本存在,如何让它返回1或0或true / false?任何帮助都表示感谢。

        $element = $this->byCssSelector('body')->text();
        $test = $this->assertRegExp('/find this text/i',$element);

        if($this->assertTrue($test)){
            echo 'text found';
        }
        else{
            echo 'not found';
        }

3 个答案:

答案 0 :(得分:20)

assertRegExp()将不会返回任何内容。如果断言失败 - 意味着找不到文本 - 则以下代码将不会被执行:

 $this->assertRegExp('/find this text/i',$element);
 // following code will not get executed if the text was not found
 // and the test will get marked as "failed"

答案 1 :(得分:4)

PHPUnit不是为了从断言中返回值而设计的。根据定义,断言意味着在失败时打破流动。

如果你需要做这样的事情,你为什么要使用PHPUnit呢?使用preg_match

 $test = preg_match('/find this text/i', $element);

 if($test) {
        echo 'text found';
 }
 else {
        echo 'text not found';
 }

答案 2 :(得分:2)

较新的 phpunit 版本中使用此方法:

$this->assertMatchesRegularExpression('/PATTERN/', $yourString);
相关问题