断言var是phpunit中没有特定字符的非空字符串

时间:2014-03-14 06:10:45

标签: php unit-testing phpunit assertions

我想声明一个变量是phpunit中的一个(非空白)字符串,但我不想断言该字符串必须匹配任何完全的字符串。

例如,我想提取一个用户名,并确保我成功获得了一些非空白用户名,但我并不确切知道我的用户名。

我可以非常容易地声明它是一个非空变量,或者它是一个完全匹配某个字符串的字符串,或断言var是没有phpunit帮助的字符串:

$this->assertNotEmpty($username);
$this->assertSame('myusername', $username);
$this->assertTrue(is_string($username));

这些都接近我所需要的,使用is_string实际测试正确的条件,但是自己做is_string还不够好,因为当测试失败时我无法获得有用的信息性消息而且,错误信息变得毫无用处,而不是告诉我实际返回了什么类型的值:

Failed asserting that false is true.

那么如何使用phpunit的断言系统断言var是string类型和非空白?

2 个答案:

答案 0 :(得分:33)

您可以将自己的消息添加到所有PHPUnit断言中,这样的内容对您有用: -

$this->assertTrue(is_string($username), "Got a " . gettype($username) . " instead of a string");

否则,您可以使用

$this->assertInternalType('string', $username, "Got a " . gettype($username) . " instead of a string");

See the manual

答案 1 :(得分:1)

从 2018 年起,assertInternalType()assertNotInternalType() 被弃用。

使用以下代替:

assertIsArray()

assertIsBool()

assertIsFloat()

assertIsInt()

assertIsNumeric()

assertIsObject()

assertIsResource()

assertIsString()

assertIsScalar()

assertIsCallable()

assertIsIterable()

assertIsNotArray()

assertIsNotBool()

assertIsNotFloat()

assertIsNotInt()

assertIsNotNumeric()

assertIsNotObject()

assertIsNotResource()

assertIsNotString()

assertIsNotScalar()

assertIsNotCallable()

assertIsNotIterable()