Assertion fail message for string contains substring [duplicate]

你。 提交于 2019-12-22 18:46:25

问题


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?


回答1:


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"


来源:https://stackoverflow.com/questions/15711180/assertion-fail-message-for-string-contains-substring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!