还有更好的方法来用jUnit编写吗

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

当前回答

另一种变体是

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

此外,在org.mockito.internal.matchers中还有一些其他有趣的匹配器,如StartWith, Contains等。

其他回答

assertj变体

import org.assertj.core.api.Assertions;
Assertions.assertThat(actualStr).contains(subStr);

如果你添加Hamcrest和JUnit4,你可以这样做:

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

使用一些静态导入,它看起来好多了:

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

所需的静态导入是:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.containsString;

另一种变体是

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

此外,在org.mockito.internal.matchers中还有一些其他有趣的匹配器,如StartWith, Contains等。

示例(junit版本- 4.13)

import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;

public class TestStr {

@Test
public void testThatStringIsContained(){
    String testStr = "hi,i am a test string";
    assertThat(testStr).contains("test");
 }

}

我写了这个效用法

public static void assertContains(String string, String subString) {
    Assertions.assertTrue(string.contains(subString));
}