Assertion fail message for string contains substring
assertions, functional-testing, java, junit, string
Solution
Use hamcrest Matcher `containsString()`
// Hamcrest assertion
assertThat(person.getName(), containsString("myName"));
// Error Message
java.lang.AssertionError:
Expected: a string containing "myName"
got: "some other name"
You can optional add an even more detail error message.
// Hamcrest assertion with custom error message
assertThat("my error message", person.getName(), containsString("myName"));
// Error Message
java.lang.AssertionError: my error message
Expected: a string containing "myName"
got: "some other name"
Problem
I have done a lot of functional testing on text outputs on text generating software lately, an find myself writing a lot of ``` assertTrue(actualString.contains(wantedString)); ``` However, the message for when this fails is something non-descriptive like ``` Expected [true], but was [false] ``` An alternative is to include a custom fail message as ``` String failMsg = String.format("Wanted string to contain: %s, Actual string: %s", wantedString, actualString); assertTrue(failMsg, actualString.contains(wantedString)); ``` But it feels a bit tedious to do this manually all the time. Is there a better way?