Hamcrest 学习指南

本贴最后更新于 1516 天前,其中的信息可能已经时移世改

Hamcrest

1、前言

Hamcrest是一款用于校验的Java的单元测试框架,可以组合创建灵活的匹配器进行断言。

官网:http://hamcrest.org/JavaHamcrest/

2、API

1、startsWith:匹配字符串以XX开头
assertThat("myStringOfNote", startsWith("my"))
2、containsString:匹配是否包含指定字符串
assertThat("myStringOfNote", containsString("ring"))
3、equalTo:基于传入对象的equals方法匹配方式,如果是数组比较每个元素是否相等。
assertThat("foo", equalTo("foo"));
assertThat(new String[] {"foo", "bar"}, equalTo(new String[] {"foo", "bar"}));
4、allOf:匹配所有指定的匹配项,可指定多个匹配条件
assertThat("myValue", allOf(startsWith("my"), containsString("Val")));
5、anyOf:匹配其中任意一个匹配项,可指定多个匹配条件
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
6、both:两个选项都匹配
assertThat("fab", both(containsString("a")).and(containsString("b")))
7、either:匹配其中任意一个匹配项
assertThat("fan", either(containsString("a")).or(containsString("b")))
8、describedAs:自定义描述匹配
describedAs(
参数1:自定义描述,可以使用占位符%0,%1,%2...
参数2:匹配器
参数3:自定义描述中需要替换的变量按先后顺序匹配);
assertThat(120,describedAs("自定义期望值:%0", equalTo(110), 110));
输出:Expected: 自定义期望值:<110>
9、everyItem:匹配现实Iterable接口类中的每个元素是否符合要求
assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))
10、is:装饰另一个匹配器,保留其行为。
assertThat(cheese, is(equalTo(smelly))) 
替代
assertThat(cheese, equalTo(smelly))
11、instanceOf:匹配对象是属于哪个类
assertThat(new Canoe(), instanceOf(Canoe.class));
12、isA:instanceOf的快捷方式
assertThat(cheese, isA(Cheddar.class))
替代
assertThat(cheese, is(instanceOf(Cheddar.class)))
13、hasItem:匹配现实Iterable接口类中的【至少有一个元素】是否符合要求
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")));
assertThat(Arrays.asList("foo", "bar"), hasItem("bar"));
//endsWith("z") and endsWith("o") 必须同时满足
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")));
//baz1 and foo 必须同时满足
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz1", "foo"));
14、not:创建一个结果相反的匹配器
assertThat(cheese, is(not(equalTo(smelly))))
assertThat(cheese, is(not(smelly)))
15、notNullValue:匹配是否非空
assertThat(cheese, is(notNullValue()))
16、nullValue:匹配是否为空
assertThat(cheese, is(nullValue())
17、containsStringIgnoringCase:匹配是否包含指定字符串,忽略大小写
assertThat("myStringOfNote", containsStringIgnoringCase("Ring"))
18、startsWithIgnoringCase:匹配字符串以XX开头,忽略大小写
assertThat("myStringOfNote", startsWithIgnoringCase("My"))
19、endsWith:匹配字符串以XX结尾
assertThat("myStringOfNote", endsWith("Note"))
20、endsWithIgnoringCase:匹配字符串以XX结尾,忽略大小写
assertThat("myStringOfNote", endsWithIgnoringCase("note"))
21、matchesRegex:匹配字符串是否满足指定正则表达式
assertThat("abc", matchesRegex(Pattern.compile("ˆ[a-z]$"));
assertThat("abc", matchesRegex("ˆ[a-z]+$"));
2 操作
luojie 在 2020-09-23 16:21:23 更新了该帖
luojie 在 2020-09-08 10:22:08 更新了该帖
回帖
请输入回帖内容 ...