我想使用PHPUnit编写一个测试,其中包括一个检查,以确保值是string
或NULL
。
AFAIK,我可以写这样一个测试:
if (is_string($value) || is_null($value)) {
$result = TRUE;
} else {
$result = FALSE;
}
$this->assertTrue($result);
然而,我看到PHPUnit有一个logicalOr()
方法,我不知道我是否应该使用它来进行更"原生"的测试?如果我应该使用它,我不知道怎么做…
使用phpunit v5.5,它(也)是这样工作的:
if (is_string($value) || is_null($value)) {
$result = TRUE;
} else {
$result = FALSE;
}
$this->assertThat($value, $this->logicalOr(
$this->isType('string'),
$this->isNull()
));
logicalOr
返回一个对象,该对象用于构建可传递给assertThat
的条件。我无法在手机上检查语法,但它应该是这样的:
self::assertThat(self::logicalOr(self::stringValue(), self::nullValue()));
方法名称无疑是不正确的,因为我习惯了Hamcrest,但我的结构是相似的。
最好的方法是在出现问题时为您提供最可用的输出。在这种情况下,我认为你这样做并不重要,只要你知道哪里出了问题。以下代码将提供一条有意义的错误消息:
$message = '$value should have been either a string or null, but was actually a '
.gettype($value);
$this->asertTrue($valueIsEitherStringOrNull, $message);