assertj-assertions-generator-maven-plugin icon indicating copy to clipboard operation
assertj-assertions-generator-maven-plugin copied to clipboard

Add option to generate chained assertions

Open MichaelBitard opened this issue 8 years ago • 3 comments

Enhancement

Use case:

  • You have an object "objectA" of type ObjectA which contains (among other fields) a field objectB of type ObjectB
  • To assert it, I do
assertThat(objectA).hasFieldOfObjectA("field");
assertThat(objectA.objectB).hasFieldOfObjectB("fieldOfObjectB");
  • I'd like to be able to assert like this:
assertThat(objectA)
  .hasFieldOfObjectA("field")
  .withObjectB()
    .hasFieldOfObjectB("fieldOfObjectB");

I already do that manually, but I think it could be useful to be able to add this behavior automatically.

What do you think?

MichaelBitard avatar Mar 24 '17 10:03 MichaelBitard

I agree on the idea, I would just use getB() to navigate to the B's assertions.

joel-costigliola avatar Mar 25 '17 04:03 joel-costigliola

I would rather prefer to see it as has<FieldName>Satisfying(Consumer/Condition) pair of methods. Just like hasValueSatisfying for Optional or satisfies for list elements or other similar asserts. This way you can continue to fluently verify other complex fields of objectA. With getB()/withObjectB() approach you have no way to fluently return back to objectA assertions.

yoorick avatar Oct 09 '18 09:10 yoorick

Something like this:

assertThat(objectA)
    .hasFieldOfObjectA("field")
    .hasObjectBSatisfying(
        objectB -> assertThat(objectB)
            .hasFieldB1("value1")
            .hasFieldB2("value2")
    )
    .hasObjectCSatisfying(
        objectC -> assertThat(objectC)
            .hasFieldC1("otherValue1")
            .hasFieldC2(1234)
            .hasFieldC3("otherValue3")
    )
    // ...

yoorick avatar Oct 09 '18 09:10 yoorick