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;
org.junit.Assert
vs junit.framework.Assert
,因为后者没有Hamcrest MatcherassertThat()
assertThat
比然后更有用assertTrue
import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.containsString;
-只是为了使某人免于麻烦
org.hamcrest.Matchers.containsString;
最新的api中的hamcrest-library
依赖项。
使用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"
在这里将我的回答贴在重复的问题上
示例(简化版-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");
}
}