How do I assert the result is an integer in PHPUnit?
PhpUnit TestingPhpunitPhp Problem Overview
I would like to be able test that a result is an integer (1,2,3...) where the function could return any number, e.g.:
$new_id = generate_id();
I had thought it would be something like:
$this->assertInstanceOf('int', $new_id);
But I get this error:
Argument #1 of PHPUnit_Framework_Assert::assertInstanceOf() must be a class or interface name
Php Solutions
Solution 1 - Php
$this->assertInternalType("int", $id);
Edit: As of PHPUnit 8, the answer is:
$this->assertIsInt($id);
Solution 2 - Php
I prefer using the official PHPUnit class constants.
PHPUnit v5.2:
use PHPUnit_Framework_Constraint_IsType as PHPUnit_IsType;
// ...
$this->assertInternalType(PHPUnit_IsType::TYPE_INT, $new_id);
Or latest which at the moment of writing is v7.0:
use PHPUnit\Framework\Constraint\IsType;
// ...
$this->assertInternalType(IsType::TYPE_INT, $new_id);
Solution 3 - Php
Original answer is given below for posterity, but I would strongly recommend using assertInternalType()
as suggested in other answers.
Original answer:
Simply use assertTrue with is_int().
$this->assertTrue(is_int($new_id));
Solution 4 - Php
I think better use this construction:
$this->assertThat($new_id, $this->logicalAnd(
$this->isType('int'),
$this->greaterThan(0)
));
because it will check not only the type of $new_id variable, but will check if this variable is greater than 0 (assume id cannot be negative or zero) and this is more strict and secure.
Solution 5 - Php
As of PHPUnit 8, The other approaches are now deprecated, assertInternalType()
will now throw this error and fail:
> assertInternalType() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertIsArray(), assertIsBool(), assertIsFloat(), assertIsInt(), assertIsNumeric(), assertIsObject(), assertIsResource(), assertIsString(), assertIsScalar(), assertIsCallable(), or assertIsIterable() instead.
It is now recommended to use assertIsNumeric()
or assertIsInt()
for this purpose.
Solution 6 - Php
This answer is for people wondering how to make sure that the result is EITHER an integer or a string of integers. (The issue appears in some comments):
$this->assertEquals( 1 , preg_match( '/^[0-9]+$/', $new_id ),
$new_id . ' is not a set of digits' );
Here we make sure preg_match returns a '1', where preg_match is testing that all string characters are digits.