I want to write a test using PHPUnit which includes a check to make sure that a value is either a string
or NULL
.
AFAIK, I can write such a test like so:
if (is_string($value) || is_null($value)) {
$result = TRUE;
} else {
$result = FALSE;
}
$this->assertTrue($result);
However, I've seen that PHPUnit has a logicalOr()
method, which I don't know if I should be using to make a more 'native' test? And if I should be using it, I can't figure out how to do so...
logicalOr
returns an object that is used to build a condition that can be passed to assertThat
. I can't check the syntax on my phone, but it should look something like this:
self::assertThat(self::logicalOr(self::stringValue(), self::nullValue()));
The method names are no doubt incorrect as I am used to Hamcrest, but I he structure is similar.
The best approach is the one which will give you the most usable output in the event of a problem. In this case, I don't think it matters too much which way you so it, as long as you know what went wrong. The following code will provide a meaningful error message:
$message = '$value should have been either a string or null, but was actually a '
.gettype($value);
$this->asertTrue($valueIsEitherStringOrNull, $message);
Using phpunit v5.5 it (also) works this way:
if (is_string($value) || is_null($value)) {
$result = TRUE;
} else {
$result = FALSE;
}
$this->assertThat($value, $this->logicalOr(
$this->isType('string'),
$this->isNull()
));