模拟框架通常不鼓励模拟数据对象。
但是,每次在测试中需要时填充数据对象可能会很不方便。
常见的方法是使用测试构建器。就像是:
public class MyDtoBuilder {
private Foo foo;
private Bar bar;
public static MyDtoBuilder aMyDto() {
return new MyDtoBuilder();
}
public MyDtoBuilder withFoo(Foo foo) {
this.foo = foo;
return this;
}
public MyDtoBuilder withBar(Bar bar) {
this.bar = bar;
return this;
}
public MyDtoBuilder withDefaults() {
return this.withFoo(new Foo(...)).withBar(new Bar(...));
}
public MyDto build() {
return new MyDto(foo,bar);
}
}现在,您可以方便地使用默认值构建DTO,然后根据需要覆盖它们。如果Foo和Bar很复杂,您也可以为这些构建器提供测试构建器,这样您就可以执行类似的操作
MyDto expectedDto = aMyDto()
.withDefaults()
.withFoo(aFoo()
.withName("testFoo"))
.build();Freeman和Pryce在“测试引导的面向对象软件”一书中详细介绍了这一点。
您应该注意区分测试构建器,这些构建器构建预先填充了合理的测试数据的对象,以及用于非测试代码的构建器(它是实例化不可变对象的常用模式)。不要跨越这些流 - 不要在非测试代码中使用测试构建器。