Does PHPUnit have an assertion that checks the type of a value
Function:
public function getTaxRate()
{
return 21;
}
I want to test that the value returned is a number.
Sorry but i am new to PHPUnit testing.
I found that SimpleTest has assertIsA(); is there something similar for PHPUnit.
Regards
The notion that something "is a number" is a little fuzzy in weakly typed languages like php. In php, 1 + "1"
is 2. Is the string "1"
a number?
The Phpunit assertion assertInternalType()
might help you:
$actual = $subject->getTaxRate();
$this->assertIternalType('int', $actual);
But you can't combine assertions with logical operators. So you can't easily express the idea "assert that 42.0 is either an integer or a float". Such more intensive assertions can be grouped into a private helper assertion method:
private function assertNumber($actual, $message = "Is a number") {
$isScalar = is_scalar($actual);
$isNumber = $isScalar && (is_int($actual) || is_float($actual));
$this->assertTrue($isNumber, $message);
}
And then you just use it in your tests within the same testcase class:
$actual = $subject->getTaxRate();
$this->assertNumber($actual);
You can write your own custom assertion as well. This is probably your best bet if you need to run a number-pseudo-type assertion often, unless I've missed something. See Extending PHPUnit which shows how that is done.
Related:
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