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
'programing' 카테고리의 다른 글
헤더 파일은 전체 프로그램에서 한 번만 포함됩니까? (0) | 2023.09.09 |
---|---|
이 버전의 응용 프로그램이 Google Play를 통한 과금을 위해 구성되지 않았습니다. (0) | 2023.09.09 |
os.아래의 디렉토리를 파고들지 않고 걸어갑니다. (0) | 2023.09.09 |
PowerShell에서 2>&1의 의미 (0) | 2023.09.09 |
Angular2 구성요소 @입력 양방향 바인딩 (0) | 2023.09.09 |