0

In my team the is a thread to write fluent assertions with AssertJ in the following way:

void checkPerson(Person person, String expectedName, Integer expectedAge) {
  assertThat(person)
    .isNotNull()
    .extracting(Person::getName, Person::getAge) 
    .containsExactly(expectedName, expectedAge)
}

but I prefer the other way:

void checkPerson(Person person, String expectedName, Integer expectedAge) {
  assertThat(person).isNotNull();
  assertThat(person.getName()).isEqualTo(expectedName);
  assertThat(person.getAge()).isEqualTo(expectedAge);
}

I think my way is more straightforward and type-safe. Are there any advantages of the first approach?

a3dsfcv
  • 1,146
  • 2
  • 20
  • 35
  • It is a matter of personal choice. Type safety is not an issue in either case. – Turing85 Sep 22 '20 at 16:11
  • This is not the question in Java, but it doesn't matter, you will find [it](https://stackoverflow.com/questions/55495026/when-would-it-be-a-good-idea-to-use-fluentassertions) useful. – Giorgi Tsiklauri Sep 22 '20 at 16:23
  • @Turing85 why type safety is not an issue? in the first case as the parameter of `containsExactly` I can pass String, String instead of String, Integer. And I get the error only in the runtime. With the second approach I get it in compile-time – a3dsfcv Sep 22 '20 at 16:24
  • @a3dsfcv the error you get is an assertion error since the types do not match. This is something i would expect in a testing framework and in line with how `equals(...)` works in general. From a fail-fast point of view, you are right. – Turing85 Sep 22 '20 at 16:26
  • What about the output? Are the error messages equivalent between the two styles when tests fail? – jaco0646 Sep 22 '20 at 16:28
  • error messages are the same, I prefer chaining assertions because I feel the code is lighter but as said in the first comment it's a matter of personal preferences. – Joel Costigliola Sep 23 '20 at 22:20

1 Answers1

0

The main benefit for me is the readability - the fluent code is (at least for me) easier to read and it takes less space. Exactly for the same reason You call the fluent methods in for instance builder classes.

marek.kapowicki
  • 674
  • 2
  • 5
  • 17