Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert a function result of boolean/string in PHPUnit

I'm using PHPUnit to auto-test my app. I want to assert the result of a function call which can return a boolean or a string. My code looks like this:

$myExample = new MyExample();
$value = $myExample->getValue();
if ($value !== false) {
  assertNotNull($value);
  assertFalse(empty($value));
}

But is it also possible to check whether the method executes successfully? Is "assertTrue($value)" the correct way?

like image 632
altralaser Avatar asked Mar 27 '17 18:03

altralaser


2 Answers

UPDATE: As per mtiziani's comment below, this answer applies for PHPUnit versions below 9.#

If you want to assert the data type of the value, the correct way would be:

$this->assertInternalType('[expected_data_type]', $value);

The [expected_data_type] PHPUnit can validate can be any of these:

'array'
'boolean'
'bool'
'float'
'integer'
'int'
'null'
'numeric'
'object'
'resource'
'string'
'scalar'
'callable'

So, to assert that the returned value is a boolean, you would:

$this->assertInternalType('bool', $value);
like image 57
confirmator Avatar answered Sep 28 '22 00:09

confirmator


UPDATE: Deprecated methods

Please use the following ones in case you want to check the data type:

assertIsArray()

assertIsBool()

assertIsFloat()

assertIsInt()

assertIsNumeric()

assertIsObject()

assertIsResource()

assertIsString()

assertIsScalar()

assertIsCallable()

assertIsIterable()

assertIsNotArray()

assertIsNotBool()

assertIsNotFloat()

assertIsNotInt()

assertIsNotNumeric()

assertIsNotObject()

assertIsNotResource()

assertIsNotString()

assertIsNotScalar()

assertIsNotCallable()

assertIsNotIterable()
like image 23
Lucía Martínez Merchán Avatar answered Sep 28 '22 02:09

Lucía Martínez Merchán