2

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?

Theodor
  • 5,536
  • 15
  • 41
  • 55
  • 2
    Personally I don't bother writing extra messages for the most part - tests rarely fail, and when they do, debug into them for more details :) – Jon Skeet Mar 29 '13 at 20:52
  • 1
    For unit tests - no, but these being functional (integration) tests, that might be running on an Jenkins server somewhere, the added level of detail is helpful. – Theodor Mar 29 '13 at 21:48

1 Answers1

7

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"
Rylander
  • 19,449
  • 25
  • 93
  • 144