编写测试以覆盖 100% 的代码是我们应该尝试实现的目标。但是我想出了我不知道如何测试方法(工厂方法)的情况:
public function getDocument(){
$document = new Document();
$document->settings(new Settings());
$document->filesystem(new Filesystem('e:'));
return $document;
}
该方法的目的是创建文档的快捷方式,而不是每次都写3行。
如何测试这个方法?
或者这就是为什么我们有 @codeCoverageIgnoreStart block 的情况?正是出于这个原因,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:'));
也许我应该考虑是否真的应该提供那个方法,想要使用文档的用户应该知道依赖关系,它不应该被隐藏。
最佳答案
这个方法有什么作用?返回初始化的 Document
对象。因此,您只需验证返回值是一个 Document
实例,并且它已设置 Settings
和 Filesystem
对象。如果您有这些的 getter 就很容易,否则您必须访问相应的属性。
测试可能听起来很基础,但它确实测试了它需要的东西。当您以注入(inject)设置和文件系统的方式重构代码时,测试仍会告诉您文档是否设置了这些属性。
之所以称为单元测试
,是因为您测试的是单元
,而不是对象或方法。如果你的单位有多个类(class),随它去吧。不需要注入(inject)所有东西,也不需要模拟所有东西——这些东西可以简化测试,但在某些情况下最好不要模拟它们
关于php - 测试工厂方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540816/