Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 448
Kzqai Avatar asked Mar 14 '14 06:03

Kzqai


2 Answers

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


This answer is now outdated. See this answer for the up to date solution.

like image 194
vascowhite Avatar answered Sep 28 '22 06:09

vascowhite


From 2018 the assertInternalType() and assertNotInternalType() are depricated.

Use instead on of the following:

assertIsArray()

assertIsBool()

assertIsFloat()

assertIsInt()

assertIsNumeric()

assertIsObject()

assertIsResource()

assertIsString()

assertIsScalar()

assertIsCallable()

assertIsIterable()

assertIsNotArray()

assertIsNotBool()

assertIsNotFloat()

assertIsNotInt()

assertIsNotNumeric()

assertIsNotObject()

assertIsNotResource()

assertIsNotString()

assertIsNotScalar()

assertIsNotCallable()

assertIsNotIterable()

like image 38
Szekelygobe Avatar answered Sep 28 '22 06:09

Szekelygobe