我正在尝试测试我编写的以下类中的方法(函数比显示的要多,基本上,每个 is_*() 方法都有一个函数):
class Validate {
private static $initialized = false;
/**
* Construct won't be called inside this class and is uncallable from the outside. This prevents
* instantiating this class. This is by purpose, because we want a static class.
*/
private function __construct() {}
/**
* If needed, allows the class to initialize itself
*/
private static function initialize()
{
if(self::$initialized) {
return;
} else {
self::$initialized = true;
//Set any other class static variables here
}
}
...
public static function isString($string) {
self::initialize();
if(!is_string($string)) throw new InvalidArgumentException('Expected a string but found ' . gettype($string));
}
...
}
当我测试这些方法是否因无效输入而引发异常时,效果非常好!然而,当我测试该方法是否按预期工作时,PHPUnit 会提示,因为我在测试中没有断言。具体错误为:
# RISKY This test did not perform any assertions
但是,我没有任何值(value)可以反对,所以我不知道如何克服这个问题。
我读过一些关于测试静态方法的内容,但这似乎主要涵盖了静态方法之间的依赖关系。此外,即使是非静态方法也可能没有返回值,那么如何解决这个问题?
仅供引用,我的测试代码:
class ValidateTest extends PHPUnit_Framework_TestCase {
/**
* @covers ../data/objects/Validate::isString
* @expectedException InvalidArgumentException
*/
public function testIsStringThrowsExceptionArgumentInvalid() {
Validate::isString(NULL);
}
/**
* @covers ../data/objects/Validate::isString
*/
public function testIsStringNoExceptionArgumentValid() {
Validate::isString("I am a string.");
}
}
最佳答案
使用 assertNull 测试 void 函数:
/**
* @covers ../data/objects/Validate::isString
*/
public function testIsStringNoExceptionArgumentValid() {
$this->assertNull( Validate::isString("I am a string.") );
}
关于php - PHPUnit 如何测试没有返回值的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27511593/