我们在代码库中广泛使用了构建器模式,所有构建对象都具有toBuilder()
方法。我想编写一个单元测试,以确保在toBuilder()
方法中没有遗忘任何字段,即对于任何可构建对象,我想大致测试如下
MyClass obj = getTestObjectWithRandomData();
assertEquals(obj, obj.toBuilder().build());
现在,我可以很容易地编写
getTestObjectWithRandomData()
的基本版本,该版本使用反射将一堆值分配给任何对象的字段。但是,问题是build()
通常包含大量的验证检查,例如,如果某个整数不在合理范围内,则会抛出异常。编写符合所有这些特定于类的验证检查的getTestObjectWithRandomData()
通用版本将是不可能的。那么,我该怎么做呢?我很想将构造代码和验证代码分为不同的方法,以使测试不会在验证过程中进行,但这意味着人们在创建对象后必须记住在对象上调用
validate()
或其他对象。不好。还有其他想法吗?
最佳答案
使用龙目岛怎么样?那是您的选择吗?它将自动生成构建器代码,您再也不必担心它。
https://projectlombok.org/features/Builder
只需使用@Builder
注释您的班级
与龙目岛
import lombok.Builder;
import lombok.Singular;
import java.util.Set;
@Builder
public class BuilderExample {
private String name;
private int age;
@Singular private Set<String> occupations;
}
香草爪哇
import java.util.Set;
public class BuilderExample {
private String name;
private int age;
private Set<String> occupations;
BuilderExample(String name, int age, Set<String> occupations) {
this.name = name;
this.age = age;
this.occupations = occupations;
}
public static BuilderExampleBuilder builder() {
return new BuilderExampleBuilder();
}
public static class BuilderExampleBuilder {
private String name;
private int age;
private java.util.ArrayList<String> occupations;
BuilderExampleBuilder() {
}
public BuilderExampleBuilder name(String name) {
this.name = name;
return this;
}
public BuilderExampleBuilder age(int age) {
this.age = age;
return this;
}
public BuilderExampleBuilder occupation(String occupation) {
if (this.occupations == null) {
this.occupations = new java.util.ArrayList<String>();
}
this.occupations.add(occupation);
return this;
}
public BuilderExampleBuilder occupations(Collection<? extends String> occupations) {
if (this.occupations == null) {
this.occupations = new java.util.ArrayList<String>();
}
this.occupations.addAll(occupations);
return this;
}
public BuilderExampleBuilder clearOccupations() {
if (this.occupations != null) {
this.occupations.clear();
}
return this;
}
public BuilderExample build() {
// complicated switch statement to produce a compact properly sized immutable set omitted.
// go to https://projectlombok.org/features/Singular-snippet.html to see it.
Set<String> occupations = ...;
return new BuilderExample(name, age, occupations);
}
@java.lang.Override
public String toString() {
return "BuilderExample.BuilderExampleBuilder(name = " + this.name + ", age = " + this.age + ", occupations = " + this.occupations + ")";
}
}
}