问题

有没有更好的方法在jUnit中编写

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

#1 热门回答(215 赞)

如果你添加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;

#2 热门回答(8 赞)

usefest assert 2.0尽可能编辑:assertj可能有更多的断言(一个分叉)

assertThat(x).contains("foo");

#3 热门回答(6 赞)

使用hamcrest MatchercontainsString()

// 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的回答


原文链接