Does anyone know a reliable way to distinguish between FALSE and NULL with PHPUnit?
I'm trying to distinguish from NULL and FALSE in return values in my assertions.
This fails:
$this->assertNotEquals(FALSE, NULL);
And these assertions pass:
$this->assertFalse(NULL);
$this->assertNull(FALSE);
Edit: For some context, this is to distinguish between an error state (FALSE) versus an empty result (NULL). To ensure the function is returning properly, I need to distinguish between the two. Thanks
Edit... As per some of the problems regarding what I am testing, I'm adding the tests.
Class testNullFalse extends PHPUnit_Framework_TestCase{
public function test_null_not_false (){
$this->assertNotEquals(FALSE, NULL, "False and null are not the same");
}
public function test_null_is_false (){
$this->assertFalse(NULL, "Null is clearly not FALSE");
}
public function test_false_is_null (){
$this->assertNull(FALSE, "False is clearly not NULL");
}
public function test_false_equals_null(){
$this->assertEquals(FALSE, NULL, "False and null are not equal");
}
public function test_false_sameas_null(){
$this->assertSame(FALSE, NULL, "False and null are not the same");
}
public function test_false_not_sameas_null(){
$this->assertNotSame(FALSE, NULL, "False and null are not the same");
}
}
And the results.
PHPUnit 3.5.10 by Sebastian Bergmann.
FFF.F.
Time: 0 seconds, Memory: 5.50Mb
There were 4 failures:
1) testNullFalse::test_null_not_false
False and null are not the same
Failed asserting that <null> is not equal to <boolean:false>.
2) testNullFalse::test_null_is_false
Null is clearly not FALSE
Failed asserting that <null> is false.
3) testNullFalse::test_false_is_null
False is clearly not NULL
Failed asserting that <boolean:false> is null.
4) testNullFalse::test_false_sameas_null
False and null are not the same
<null> does not match expected type "boolean".
FAILURES!
Tests: 6, Assertions: 6, Failures: 4.
These assertions use ==
which will perform type coercion. Hamcrest has identicalTo($value)
which uses ===
, and I believe PHPUnit has assertSame($expected, $actual)
which does the same.
self::assertSame(false, $dao->getUser(-2));
Update: In answer to your comment, "It can be NULL or an object":
$user = $dao->getUser(-2);
self::assertTrue($user === null || is_object($user));
Using Hamcrest assertions is a little more expressive, especially in the event of a failure:
assertThat($dao->getUser(-2), anyOf(objectValue(), nullValue()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With