4

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?

ps0604
  • 1,227
  • 23
  • 133
  • 330
  • I am not sure if you can break the assertion to two steps, one for `ClassB.sk` and the other for `ClassB.lista` (ignoring `sk`). Looking it up.. – Nikos M. May 03 '20 at 19:38
  • 1
    you can always use a [custom comparator](https://assertj.github.io/doc/#assertj-core-recursive-comparison-comparators) though – Nikos M. May 03 '20 at 19:42
  • @Nikos I cannot tell from your link how to compare (or ignore) a field from a specific class. – ps0604 May 03 '20 at 20:45
  • 1
    You can create a custom comparator for Fields of RecursiveAssertion. In this comparator you will check the sk key of classB but ignore the sk keys of ClassA in lista for example – Nikos M. May 03 '20 at 20:47
  • I agree with Nikos, register a comparator for ClassA that ignores the sk field. – Joel Costigliola May 04 '20 at 05:13
  • btw why dont you do two different assertions, one recursive where you ignore sk field and one only for sk field of classB? In any case reading about custom comparators is a big plus in making any custom assertion – Nikos M. May 04 '20 at 14:26

1 Answers1

6

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);
Josef Cech
  • 2,115
  • 16
  • 17
  • I've read about nested fields but lista is a list, not a single structured field, so i'm not sure this will work, it would need a key like `.ignoringFields("lista.*.sk")` – Nikos M. May 04 '20 at 14:27