我正在尝试测试我编写的以下类中的方法(比所示更多的函数,基本上每个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
然而,我没有任何值可以断言,所以我不确定如何克服这个问题。
我已经阅读了一些关于测试静态方法的文章,但那似乎主要涵盖了静态方法之间的依赖关系。此外,即使非静态方法也可能没有返回值,那么如何解决这个问题呢?
供参考,我的测试代码:
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.");
}
}
is_string()
,我在函数中使用了它。然而,由于我使用异常处理,我不想在各处编写新异常的代码。拥有一个验证类并不罕见。我理解你所说关于类的工作方式,并且你提出了一些有价值的观点。然而,你指出的方式不是我设计的方式,虽然我的设计可能在一般情况下并不完美,但对于我正在做的事情来说,这就是我认为应该的方式。 - Matthew Herbst