Assert that a var is a non-empty string of no particular characters in phpunit

Kzqai picture Kzqai · Mar 14, 2014 · Viewed 16.7k times · Source

I want to assert that a variable is a (non-blank) string in phpunit, but I don't want to assert that the string has to match any exact string.

For example, I want to pull a username, and ensure that I successfully got some non-blank username, but I don't care exactly which username I got.

I can pretty easily assert that it's a non-empty variable, or that it is a string exactly matching some string, or assert that the var is a string without phpunit's help:

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

These are all close to what I need, with the use of is_string actually testing for the right conditions, but doing the is_string myself isn't quite good enough because when the test fail I can't get a useful, informative message any more, instead of telling me what type of value was actually returned, the error message becomes the useless:

Failed asserting that false is true.

So how can I assert that a var is of type string and non-blank using phpunit's assert system?

Answer

vascowhite picture vascowhite · Mar 14, 2014

You can add your own messages to all PHPUnit assertions, something like this should work for you:-

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

Otherwise, you could use

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

See the manual