4

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

Liam
  • 536
  • 8
  • 23
  • The correct equivalent for simple-test `assertIsA();` actually is Phpunit `assertInstanceOf();`. Please double-check you mean the right assertion from simpletest and perhaps provide reference. I refer to: http://simpletest.org/api/SimpleTest/UnitTester/UnitTestCase.html#assertIsA – hakre Sep 27 '13 at 14:44

1 Answers1

8

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:

Community
  • 1
  • 1
Mike Sherrill 'Cat Recall'
  • 91,602
  • 17
  • 122
  • 185