java assert用法 - 在jUnit中對字符串AssertContains




3 Answers

如果你添加Hamcrest和JUnit4,你可以這樣做:

String x = "foo bar";
Assert.assertThat(x, CoreMatchers.containsString("foo"));

隨著一些靜態進口,它看起來好多了:

assertThat(x, containsString("foo"));

所需的靜態導入將是:

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
assertequals string

有沒有更好的方式來寫入jUnit

String x = "foo bar";
Assert.assertTrue(x.contains("foo"));



使用hamcrest Matcher containsString()

// Hamcrest assertion
assertThat(person.getName(), containsString("myName"));

// Error Message
java.lang.AssertionError:
Expected: a string containing "myName"
     got: "some other name"

您可以選擇添加更詳細的錯誤消息。

// 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"

here發表我的答案重複的問題




另一個變種是

Assert.assertThat(actual, new Matches(expectedRegex));

此外,在org.mockito.internal.matchers還有一些其他有趣的匹配器,如StartWithContains




Related