使用PHPUnit区分NULL和FALSE

Kyl*_*ppd 13 php null phpunit unit-testing

有没有人知道用PHPUnit区分FALSE和NULL的可靠方法?

我试图在断言中的返回值中区分NULL和FALSE.

这失败了:

$this->assertNotEquals(FALSE, NULL);
Run Code Online (Sandbox Code Playgroud)

这些断言通过:

$this->assertFalse(NULL);
$this->assertNull(FALSE);
Run Code Online (Sandbox Code Playgroud)

编辑:对于某些上下文,这是为了区分错误状态(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");
    }
}
Run Code Online (Sandbox Code Playgroud)

结果.

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.
Run Code Online (Sandbox Code Playgroud)

Dav*_*ess 19

这些断言用于==执行类型强制.Hamcrest identicalTo($value)使用的===,我相信PHPUnit也有assertSame($expected, $actual)相同的功能.

self::assertSame(false, $dao->getUser(-2));
Run Code Online (Sandbox Code Playgroud)

更新:在回答您的评论时,"它可以是NULL或对象":

$user = $dao->getUser(-2);
self::assertTrue($user === null || is_object($user));
Run Code Online (Sandbox Code Playgroud)

使用Hamcrest断言更具表现力,特别是在发生故障时:

assertThat($dao->getUser(-2), anyOf(objectValue(), nullValue()));
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。也许你可以帮助我解决一个哲学问题以及处理这个问题......如果 assertFalse、assertTrue、assertNull 等进行强制类型转换,它们的意义何在? (2认同)

Jon*_*nah 6

自己执行比较,并使用strict类型运算符.

$this->assertTrue(false !== null);
Run Code Online (Sandbox Code Playgroud)

http://php.net/operators.comparison