programing

How do I assert the result is an integer in PHPUnit?

lastmoon 2023. 9. 9. 10:06
반응형

How do I assert the result is an integer in PHPUnit?

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

$this->assertInternalType("int", $id);

Edit: As of PHPUnit 8, the answer is:

$this->assertIsInt($id);

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);

후손들을 위해 원답은 아래에 제시되어 있지만, 저는 강력하게 사용할 것을 추천합니다.assertInternalType()다른 답변에서 제시한 바와 같이


Original answer:

Simply use assertTrue with is_int().

$this->assertTrue(is_int($new_id));

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.

PHP 8호기 기준으로, 다른 접근법들은 이제 더 이상 사용되지 않습니다.assertInternalType()이제 이 오류를 던지고 실패합니다.

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.

이제 사용할 것을 권장합니다.assertIsNumeric()아니면assertIsInt()이를 위하여

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.

ReferenceURL : https://stackoverflow.com/questions/21654368/how-do-i-assert-the-result-is-an-integer-in-phpunit

반응형