有没有人知道用PHPUnit区分FALSE和NULL的可靠方法?
我试图在断言中的返回值中区分NULL和FALSE。
这失败了:
$this->assertNotEquals(FALSE, NULL);
这些断言通过:
$this->assertFalse(NULL);
$this->assertNull(FALSE);
编辑:对于某些上下文,这是为了区分错误状态(FALSE)和空结果(NULL)。为了确保功能正常返回,我需要区分这两者。 感谢
编辑... 根据我正在测试的一些问题,我正在添加测试。
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");
}
}
结果。
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.
答案 0 :(得分:19)
这些断言使用==
来执行类型强制。 Hamcrest的identicalTo($value)
使用===
,我相信PHPUnit的assertSame($expected, $actual)
也是如此。
self::assertSame(false, $dao->getUser(-2));
更新:在回答您的评论时,“它可以是NULL或对象”:
$user = $dao->getUser(-2);
self::assertTrue($user === null || is_object($user));
使用Hamcrest断言更具表现力,特别是在发生故障时:
assertThat($dao->getUser(-2), anyOf(objectValue(), nullValue()));
答案 1 :(得分:6)
答案 2 :(得分:1)
@David与assertSame(+1)是对的,它会为你做===严格比较。
但是让我问你:
您使用的是哪个版本的phpunit?
这个断言:
$this->assertFalse(null);
应该产生和错误!
<?php
class mepTest extends PHPUnit_Framework_TestCase {
public function testFalseNull() {
$this->assertFalse(null);
}
public function testNullFalse() {
$this->assertNull(false);
}
}
phpunit mepTest.php
PHPUnit 3.5.12 by Sebastian Bergmann.
FF
Time: 0 seconds, Memory: 3.00Mb
There were 2 failures:
1) mepTest::testFalseNull
Failed asserting that <null> is false.
/home/.../mepTest.php:6
2) mepTest::testNullFalse
Failed asserting that <boolean:false> is null.
/home/.../mepTest.php:10
FAILURES!
Tests: 2, Assertions: 2, Failures: 2.