import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; import java.util.Arrays; import java.util.List; public class HamcrestExampleTest { @Test public void testStringMatchers() { String str = "Hello, world!"; MatcherAssert.assertThat(str, Matchers.equalTo("Hello, world!")); MatcherAssert.assertThat(str, Matchers.startsWith("Hello")); MatcherAssert.assertThat(str, Matchers.endsWith("!")); MatcherAssert.assertThat(str, Matchers.containsString(",")); MatcherAssert.assertThat(str, Matchers.matchesRegex("^[A-Za-z, !]+$")); } @Test public void testCollectionMatchers() { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); MatcherAssert.assertThat(numbers, Matchers.hasSize(5)); MatcherAssert.assertThat(numbers, Matchers.contains(1, 2, 3, 4, 5)); MatcherAssert.assertThat(numbers, Matchers.everyItem(Matchers.greaterThan(0))); } @Test public void testNumberMatchers() { int number = 10; double decimal = 3.14; MatcherAssert.assertThat(number, Matchers.greaterThan(5)); MatcherAssert.assertThat(decimal, Matchers.closeTo(3, 0.1)); } }


上一篇:
下一篇:
切换中文