我最近一直在使用Hamcrest库来编写一些测试并且相当成功,但现在我需要做一些更复杂的事情并开始看到很多困难.我需要inpsect并验证Map中项目的属性.我的生产代码看起来像这样:
Map<String, List<MyItem>> map = new HashMap<String, List<MyItem>>();
map.put("one", Arrays.asList(new MyItem("One")));
map.put("two", Arrays.asList(new MyItem("Two")));
map.put("three", Arrays.asList(new MyItem("Three")));
Run Code Online (Sandbox Code Playgroud)
我想写一些测试代码,如下所示,但它不编译.看起来Hamcrest的hasEntry是类型参数化的,而hasItem和hasProperty只期望Object.
assertThat(map, Matchers.<String, List<MyItem>>hasEntry("one", hasItem(hasProperty("name", is("One")))));
Run Code Online (Sandbox Code Playgroud)
我的IDE(Eclipse)给出了以下错误消息:参数<String, List<HamcrestTest.MyItem>>hasEntry(String, List<HamcrestTest.MyItem>)化类型的方法Matchers不适用于参数(String, Matcher<Iterable<? super Object>>).首先,我认为Eclipse对于hasEntry我想使用哪种方法感到困惑,应该是hasEntry(org.hamcrest.Matcher<? super K> keyMatcher, org.hamcrest.Matcher<? super V> valueMatcher),而不是hasEntry(K key, V value).
我应该放弃并从地图中获取项目并手动检查每个属性吗?有更干净的方式吗?
在我的请求处理程序中,我想做一些验证,并根据验证检查的结果,我将返回不同的响应(成功/错误).因此,我为响应对象创建了一个抽象类,并为失败案例和成功案例创建了2个子类.代码看起来像这样,但它不编译,抱怨errorResponse和successResponse无法转换为AbstractResponse.
我是Java Generic和Spring MVC的新手,所以我不知道解决这个问题的简单方法.
@ResponseBody ResponseEntity<AbstractResponse> createUser(@RequestBody String requestBody) {
if(!valid(requestBody) {
ErrorResponse errResponse = new ErrorResponse();
//populate with error information
return new ResponseEntity<> (errResponse, HTTPStatus.BAD_REQUEST);
}
createUser();
CreateUserSuccessResponse successResponse = new CreateUserSuccessResponse();
// populate with more info
return new ResponseEntity<> (successResponse, HTTPSatus.OK);
}
Run Code Online (Sandbox Code Playgroud)