问题描述
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);
您也可以编写自己的自定义断言.如果您需要经常运行数字伪类型断言,这可能是您最好的选择,除非我错过了什么.请参阅 Extending 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.
相关:
这篇关于assertIsA 的 PHP 单元测试版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!