Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit Testing version of assertIsA

Tags:

phpunit

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

like image 457
Liam Avatar asked Feb 16 '23 05:02

Liam


1 Answers

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:

  • What's the correct way to test if a variable is a number in PHP?
  • http://php.net/is_numeric
like image 145
Mike Sherrill 'Cat Recall' Avatar answered Mar 23 '23 16:03

Mike Sherrill 'Cat Recall'