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.:
我希望能够测试结果是一个整数(1,2,3 ...),其中函数可以返回任何数字,例如:
$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
PHPUnit_Framework_Assert :: assertInstanceOf()的参数#1必须是类或接口名称
4 个解决方案
#1
89
$this->assertInternalType("int", $id);
#2
22
I prefer using the official PHPUnit class constants.
我更喜欢使用官方的PHPUnit类常量。
PHPUnit v5.2:
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:
或者最新的写作时刻是v7.0:
use PHPUnit\Framework\Constraint\IsType;
// ...
$this->assertInternalType(IsType::TYPE_INT, $new_id);
#3
15
Original answer is given below for posterity, but I would strongly recommend using assertInternalType()
as suggested in other answers.
下面给出后代的原始答案,但我强烈建议使用其他答案中建议的assertInternalType()。
Original answer:
原始答案:
Simply use assertTrue with is_int().
只需将assertTrue与is_int()一起使用即可。
$this->assertTrue(is_int($new_id));
#4
2
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.
因为它不仅会检查$ new_id变量的类型,还会检查这个变量是否大于0(假设id不能为负或零),这更加严格和安全。
#1
89
$this->assertInternalType("int", $id);
#2
22
I prefer using the official PHPUnit class constants.
我更喜欢使用官方的PHPUnit类常量。
PHPUnit v5.2:
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:
或者最新的写作时刻是v7.0:
use PHPUnit\Framework\Constraint\IsType;
// ...
$this->assertInternalType(IsType::TYPE_INT, $new_id);
#3
15
Original answer is given below for posterity, but I would strongly recommend using assertInternalType()
as suggested in other answers.
下面给出后代的原始答案,但我强烈建议使用其他答案中建议的assertInternalType()。
Original answer:
原始答案:
Simply use assertTrue with is_int().
只需将assertTrue与is_int()一起使用即可。
$this->assertTrue(is_int($new_id));
#4
2
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.
因为它不仅会检查$ new_id变量的类型,还会检查这个变量是否大于0(假设id不能为负或零),这更加严格和安全。