我希望能够测试结果是否为整数(1,2,3 ...),其中函数可以返回任何数字,例如:
$new_id = generate_id();
我以为会是这样的:
$this->assertInstanceOf('int', $new_id);
但是我得到这个错误:
PHPUnit_Framework_Assert :: assertInstanceOf()的参数#1必须为类或接口名称
$this->assertInternalType("int", $id);
编辑:从PHPUnit 8开始,答案是:
$this->assertIsInt($id);
我更喜欢使用官方的PHPUnit类常量。
PHPUnit v5.2:
use PHPUnit_Framework_Constraint_IsType as PHPUnit_IsType;
// ...
$this->assertInternalType(PHPUnit_IsType::TYPE_INT, $new_id);
或在撰写本文时为v7.0的最新版本:
use PHPUnit\Framework\Constraint\IsType;
// ...
$this->assertInternalType(IsType::TYPE_INT, $new_id);
以下是后代的原始答案,但我强烈建议assertInternalType()
按照其他答案的建议使用。
原始答案:
只需将assertTrue与is_int()一起使用。
$this->assertTrue(is_int($new_id));
我认为最好使用这种构造:
$this->assertThat($new_id, $this->logicalAnd(
$this->isType('int'),
$this->greaterThan(0)
));
因为它不仅会检查$ new_id变量的类型,而且会检查此变量是否大于0(假设id不能为负或零),并且这样做更加严格和安全。
从PHPUnit 8开始,不推荐使用其他方法,现在assertInternalType()
将抛出此错误并失败:
assertInternalType()已弃用,并将在PHPUnit 9中删除。重构测试以使用assertIsArray(),assertIsBool(),assertIsFloat(),assertIsInt(),assertIsNumeric(),assertIsObject(),assertIsResource(),assertIsString(), assertIsScalar(),assertIsCallable()或assertIsIterable()代替。
现在建议使用assertIsNumeric()
或assertIsInt()
用于此目的。
这个答案是给那些想知道如何确保结果是整数还是整数字符串的人的。(问题出现在一些注释中):
$this->assertEquals( 1 , preg_match( '/^[0-9]+$/', $new_id ),
$new_id . ' is not a set of digits' );
在这里,我们确保preg_match返回一个“ 1”,其中preg_match正在测试所有字符串字符是否都是数字。
文章标签:php , phpunit , unit-testing
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
评论已关闭!