英文:
Ignoring only embedded member in AssertJ
问题
我有两个类需要用`JUnit`/`Mockito`进行测试:
public class ClassA {
private int sk;
// getters and setters
}
public class ClassB {
private int sk;
private List<ClassA> lista;
// getters and setters
}
然后在我的测试类中,使用`AssertJ`:
List<ClassA> lista = //... 用ClassA对象的列表填充
ClassB expected = new ClassB();
expected.setSk(5);
expected.setLista(lista);
ClassB actual = getItFromTheClassToTest();
assertThat(actual).usingRecursiveComparison()
.ignoringFields("sk") // 需要仅在ClassA中忽略sk字段
.isEqualTo(expected);
问题是`sk`字段在两个类中都存在,我需要仅在`ClassA`中忽略它,而不是在`ClassB`中忽略。这在`AssertJ`中是否可行?
英文:
I have two classes to test with JUnit
/Mockito
:
public class ClassA {
private int sk;
// getters and setters
}
public class ClassB {
private int sk;
private List<ClassA> lista;
// getters and setters
}
Then in my test class, using AssertJ
:
List<ClassA> lista = //... populated with list of objects of ClassA
ClassB expected = new ClassB();
expected.setSk(5);
expected.setLista(lista);
ClassB actual = getItFromTheClassToTest();
assertThat(actual).usingRecursiveComparison()
.ignoringFields("sk") // need to ignore only classA.sk
.isEqualTo(expected);
The problem is that the name sk
is in both classes, and I need to ignore it only in ClassA
, not in ClassB
. Is this possible in AssertJ
?
答案1
得分: 6
根据ignoringFields
的Javadoc:
> 嵌套字段可以像这样指定:home.address.street
。
...所以使用您的类:
ClassB b = new ClassB(1, Arrays.asList(new ClassA(1)));
ClassB bIsEqualsExceptForNestedField = new ClassB(1, Arrays.asList(new ClassA(2)));
ClassB bIsNotEquals = new ClassB(2, Arrays.asList(new ClassA(3)));
// 应该成功
assertThat(b)
.usingRecursiveComparison()
.ignoringFields("lista.sk")
.isEqualTo(bIsEqualsExceptForNestedField);
// 应该失败
assertThat(b)
.usingRecursiveComparison()
.ignoringFields("lista.sk")
.isEqualTo(bIsNotEquals);
英文:
According to the ignoringFields
javadoc:
> Nested fields can be specified like this: home.address.street
.
...so with your classes:
ClassB b = new ClassB(1, Arrays.asList(new ClassA(1)));
ClassB bIsEqualsExceptForNestedField = new ClassB(1, Arrays.asList(new ClassA(2)));
ClassB bIsNotEquals = new ClassB(2, Arrays.asList(new ClassA(3)));
// should succeed
assertThat(b)
.usingRecursiveComparison()
.ignoringFields("lista.sk")
.isEqualTo(bIsEqualsExceptForNestedField);
// should fail
assertThat(b)
.usingRecursiveComparison()
.ignoringFields("lista.sk")
.isEqualTo(bIsNotEquals);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论