似乎测试界的普遍共识是
不
测试私有方法。相反,你应该
test private methods by testing the public methods that invoke them
. 但是,我觉得有些事情不对劲。让我们以这个方法为例:
/**
* Returns the base name of the output generator class. If the class is named
* Reno_OutputGenerator_HTML, this would return "HTML".
*
* @return string
*/
protected function getName()
{
$class = get_class($this);
$matches = array();
if (preg_match('/^Reno_OutputGenerator_(.+)$', $class, $matches))
{
return $matches[1];
}
else
{
throw new Reno_OutputGenerator_Exception('Class name must follow the format of Reno_OutputGenerator_<name>.');
}
}
这个特殊的函数在我们班的几个地方使用。我想测试
if
这个函数中的语句,这意味着对于每个公共函数,我必须测试这两种情况以及公共方法本身所做的其他操作。
这就是我觉得奇怪的地方。如果我在测试
getName()
在满足特定条件时引发异常,这意味着我必须知道私有方法的实现细节。如果我必须知道这一点,那么为什么我不应该扩展类,公开方法,然后用这种方式测试它呢?
(顺便说一句:如果您想知道为什么会存在这样一个奇怪的方法,可以使用这个方法自动确定这个类的模板文件存储在哪个目录中)。