-
I have the case where I want assert that the thrown exception contains one of several possible strings in the error message. What is the best way to achieve something like this: assertThatThrownBy(() -> {
/* code to test */
})
.isInstanceOf(CertPathValidatorException.class)
.hasMessageContaining(
either( // this is pseudo code
"could not be determined",
"could not determine revocation status",
"revocation status check failed"
)
) Another case would be assertThatThrownBy(() -> {
/* code to test */
})
.isInstanceOf(CertPathValidatorException.class)
.hasMessageContaining(
// pseudo code
System.getProperty("java.vm.vendor").contains("IBM")
? "has been revoked for an unspecified reason"
: either(
"could not determine revocation status",
"revocation status check failed"
)
) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Another option that can be used is assertThatThrownBy(() -> {
/* code to test */
})
.isInstanceOf(CertPathValidatorException.class)
.extracting(Throwable::getMessage, as(InstanceOfAssertFactories.STRING))
.containsAnyOf(
"could not be determined",
"could not determine revocation status",
"revocation status check failed"
); We could add a navigational method to get the message as a string assertion, that would shorten a bit the assertThatThrownBy(() -> {
/* code to test */
})
.isInstanceOf(CertPathValidatorException.class)
.message() // returns StringAssert
.containsAnyOf(
"could not be determined",
"could not determine revocation status",
"revocation status check failed"
); Readability-wise, I'm not sure what is the best way to handle the conditional string under CharSequence[] messages = System.getProperty("java.vm.vendor").contains("IBM")
? new CharSequence[] { "has been revoked for an unspecified reason" }
: new CharSequence[] { "could not determine revocation status", "revocation status check failed" };
assertThatThrownBy(() -> {
/* code to test */
})
.isInstanceOf(CertPathValidatorException.class)
.extracting(Throwable::getMessage, as(InstanceOfAssertFactories.STRING))
.containsAnyOf(messages); |
Beta Was this translation helpful? Give feedback.
hasMessageMatching
might be an alternative for some cases. Not the best readability, though.Another option that can be used is
extracting(Function, InstanceOfAssertFactory)
:We could add a navigational method to get the message as a string assertion, that would shorten a bit the
extracting
line. It would allow writing something like: