【发布时间】:2015-09-14 20:34:53
【问题描述】:
编写测试以覆盖 100% 的代码是我们应该尝试实现的目标。但是我想出了我不知道如何测试方法(工厂方法)的情况:
public function getDocument(){
$document = new Document();
$document->settings(new Settings());
$document->filesystem(new Filesystem('e:'));
return $document;
}
该方法的目的是创建文档的快捷方式,而不是每次都写3行。
如何测试这个方法?
或者这可能是我们有@codeCoverageIgnoreStart 块的情况?正是因为这个原因,PHPUnit 才提供这种注解。
编辑: 这种方法背后的主要思想是让客户生活更轻松。仅此而已,无需配置等(但该方法将是这样做的好地方)。
//I don't want bother client with Settings() and Filesystem('e:')
$document = new Document(new Settings(), new Filesystem()); //NO
$document = Files.getDocument() //much easier and shorter.
//Changing API to getDocument($var, $var) make no sense, the same thing I could have normally.
$document = new Document(new Settings(),new Filesystem('e:'));
也许我应该考虑是否真的应该提供该方法,想要使用文档的用户应该知道依赖关系,它不应该被隐藏。
【问题讨论】:
-
有什么问题?对于这种方法,需要测试文档是否有明确的设置和文件系统。
-
当然,我现在就是这样。但是在单元测试中我们不应该依赖依赖,所以即使尚未定义 Settings 或 Filesystem 类,测试也应该通过。
-
@tne 说正确的答案。阅读依赖注入in this article。
标签: php unit-testing phpunit