似乎测试社区的普遍共识是不测试私有方法。相反,您应该通过测试调用它们的公共方法来测试私有方法。但是,我觉得有些不对劲。我们以这个方法为例:
/**
* 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()
在满足某个特定条件时抛出异常,那么这意味着我必须知道私有方法的实现细节。如果我必须知道这一点,那么为什么我不应该扩展类,公开方法并以这种方式测试呢?
(顺便说一句:如果你想知道为什么存在这样一个奇怪的方法,这是用来自动找出这个类的模板文件存储在哪个目录中的)。