piy*_*iyo 2 java unit-testing builder
我们在代码库中广泛使用构建器模式,构建的对象都有一个toBuilder()方法。我想编写一个单元测试来确保方法中没有忘记任何字段toBuilder(),即对于任何可构建的对象,我想大致像这样进行测试
MyClass obj = getTestObjectWithRandomData();
assertEquals(obj, obj.toBuilder().build());
Run Code Online (Sandbox Code Playgroud)
现在,我可以很容易地编写一个基本版本,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;
}
Run Code Online (Sandbox Code Playgroud)
香草爪哇
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 + ")";
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6378 次 |
| 最近记录: |