该项目使用TestNg,Java11,Spring测试
我正在为API编写testNG测试 我有一个具有这种结构的Java对象:
class Object1
private Object2 o2;
private List<Object3> o3;
Object2
不仅由原始属性组成。
我想测试2个Object1
是否等于以下规则:
o2
为空,即使另一个o2
也不为空,也不要失败o3
为空或为空,即使另一个o3
并非为空,也不要失败o3
不为空也不为空,则仅比较非空的Object3
字段总而言之,我想断言2个对象是相同的,递归地忽略空字段。
我可以做到
assertThat(actual).usingRecursiveComparison().ignoringActualNullFields().isEqualTo(other);
但不会忽略递归null字段。
我该如何解决?
答案 0 :(得分:0)
对我来说,以下代码有效:
public class SocialLink {
private String platform;
private String link;
}
SocialLink obj1 = new SocialLink("Facebook", null);
SocialLink obj2 = new SocialLink("Facebook", null);
assertThat(obj1).isEqualToIgnoringNullFields(obj2);
答案 1 :(得分:0)
我终于这样创建了自己的断言:
import org.assertj.core.api.AbstractAssert;
import org.assertj.core.api.Assertions;
import java.util.List;
import java.util.stream.Collectors;
public class Object1Assert extends AbstractAssert<Object1Assert, Object1> {
public Object1Assert isEqualTo(Object1 other) {
// specially for null
if(actual == other) {return this;}
if(actual.getObject2() != null) {
Assertions.assertThat(other.getObject2()).isEqualToIgnoringNullFields(actual.getObject2());
}
if(actual.getObject3() != null) {
for(Object3 object3 : actual.getObject3()) {
my.package.Assertions.assertThat(object3).isIn(other.getObject3());
}
}
// return the current assertion for method chaining
return this;
}
public Object1Assert(Object1 actual) {
super(actual, Object1Assert.class);
}
public static Object1Assert assertThat(Object1 actual) {
return new Object1Assert(actual);
}
}
public class Assertions {
public static Object3Assert assertThat(Object3 actual) {
return new Object3Assert(actual);
}
}
public class Object3Assert extends AbstractAssert<Object3Assert, Object3> {
public Object3Assert isIn(List<Object3> others) {
List<String> otherStringIds = others.stream().map(Object3::getStringId).collect(Collectors.toList());
Assertions.assertThat(otherStringIds).isNotEmpty();
Assertions.assertThat(actual.getStringId()).isIn(otherStringIds);
for (Object3 otherObject3 : others) {
if(actual.getStringId().equalsIgnoreCase(otherObject3.getStringId())) {
Assertions.assertThat(otherObject3).usingComparatorForType(Comparators.bigDecimalComparator, BigDecimal.class).isEqualToIgnoringNullFields(actual);
}
}
// return the current assertion for method chaining
return this;
}
public Object3Assert(Object3 actual) {
super(actual, Object3Assert.class);
}
public static Object3Assert assertThat(Object3 actual) {
return new Object3Assert(actual);
}
}
我为本教程需要的每种类型创建了此类 https://www.baeldung.com/assertj-custom-assertion