问题描述
PHPUnit是否有一个断言来检查值的类型
Does PHPUnit have an assertion that checks the type of a value
功能:
public function getTaxRate()
{
return 21;
}
我要测试返回的值是一个数字.
I want to test that the value returned is a number.
对不起,但是我是PHPUnit测试的新手.
Sorry but i am new to PHPUnit testing.
我发现SimpleTest具有assertIsA(); PHPUnit有类似的东西吗?
I found that SimpleTest has assertIsA(); is there something similar for PHPUnit.
致谢
推荐答案
在像php这样的弱类型语言中,是数字"的概念有些模糊.在php中,1 + "1"
是2.字符串"1"
是数字吗?
The notion that something "is a number" is a little fuzzy in weakly typed languages like php. In php, 1 + "1"
is 2. Is the string "1"
a number?
Phpunit断言assertInternalType()
可能会帮助您:
The Phpunit assertion assertInternalType()
might help you:
$actual = $subject->getTaxRate();
$this->assertIternalType('int', $actual);
但是您不能将断言与逻辑运算符结合在一起.因此,您不能轻易表达断言42.0是整数还是浮点数"的想法.可以将此类更密集的断言分组为私有帮助程序断言方法:
But you can't combine assertions with logical operators. So you can't easily express the idea "assert that 42.0 is either an integer or a float". Such more intensive assertions can be grouped into a private helper assertion method:
private function assertNumber($actual, $message = "Is a number") {
$isScalar = is_scalar($actual);
$isNumber = $isScalar && (is_int($actual) || is_float($actual));
$this->assertTrue($isNumber, $message);
}
然后,您只需在同一测试用例类中的测试中使用它即可:
And then you just use it in your tests within the same testcase class:
$actual = $subject->getTaxRate();
$this->assertNumber($actual);
您也可以编写自己的自定义断言.如果您需要经常运行数字伪类型的断言,这可能是最好的选择,除非我错过了一些事情.请参见扩展PHPUnit ,其中显示了该操作的完成方式.
You can write your own custom assertion as well. This is probably your best bet if you need to run a number-pseudo-type assertion often, unless I've missed something. See Extending PHPUnit which shows how that is done.
相关:
- What's the correct way to test if a variable is a number in PHP?
- http://php.net/is_numeric
这篇关于PHPUnit Testing版本的assertIsA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!