Assertj-core: Add hasMessage to AbstractThrowableAssert that returns StringAssert

Created on 21 Sep 2018  路  4Comments  路  Source: assertj/assertj-core

Summary

We would like to use all String assertions on an exception message. Therefore, we would like to add hasMessage to AbstractThrowableAssert that returns StringAssert. Then it would be possible to use all String assertions on it.

/cc @georgberky

Example

 assertThatThrownBy(() -> foo.bar())
                .hasMessage().startWith("example")

All 4 comments

@joel-costigliola we would like to ask you if this interferes with your plans for the fluent API. If not, we can propose a PR.

I'm not too keen on doing that for a few reasons:

  • it does not read nicely
  • it prevents chaining other exception assertions
  • it is not obvious that calling hasMessage actual switches to String assertions.

The new asString can help as it returns String assertions for the object under test toString() value which for exception contains the error message as per https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#toString--.

I can see your point about switching to String assersions not being obvious for the user. The ideal result would look like a delegate to StringAssert with a prefix of hasMessage. In Groovy I would use the @Delegate annotation. Lombok has this annotation too, but I'm not a big fan of this library. In plain Java I don't know of any convenient way to accomplish this. Adding assertions to ThrowableAssert as soon as we add them to StringAssert seems bothersome.

Would you just postpone or close the ticket for now until there's a better way to accomplish this?

Not ideal I know but I rather add assertions on the go to AbstractThrowableAssert when a user actually report one is missing and had a real life need of it.

AssertJ Core has a policy of having no hard dependencies, that prevent using 3rd party libraries.

I'm closing this ticker since it won't result in direct work but feel free to continue the conversation if you have something to add.

Was this page helpful?
0 / 5 - 0 ratings