忽略只有嵌套成员的AssertJ。

huangapple go评论73阅读模式
英文:

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&lt;ClassA&gt; lista;

    // getters and setters
 
} 

Then in my test class, using AssertJ:

   List&lt;ClassA&gt; 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(&quot;sk&quot;)  // 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(&quot;lista.sk&quot;)
    .isEqualTo(bIsEqualsExceptForNestedField);
// should fail
assertThat(b)
    .usingRecursiveComparison()
    .ignoringFields(&quot;lista.sk&quot;)
    .isEqualTo(bIsNotEquals);

huangapple
  • 本文由 发表于 2020年5月4日 03:31:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/61580478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定