使用Mockito模拟UriInfo并且响应不如预期

时间:2015-12-04 19:44:20

标签: unit-testing mockito

我正在尝试模拟UriInfo对象传递给一个宁静的服务方法,响应应该是List如果使用正确的QueryParams成功请求,并且在发生任何错误或失败的情况下StatusResponse,我发送一个正确的请求但是控制器收到它如果我发送了一个没有QueryParams的错误请求,并给我一个状态响应对象。

RestController.java

服务方式:

public Response getObjectives(@Context UriInfo info) {
try {

return Response.ok(objectiveService.getObjectives(info.getQueryParameters())).build();

} catch (Exception e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(StatusResponse.EXPIRED_SESSION).build();
}
}

RestControllerTest.java

private UriInfo mockUriInfo(String uri) throws URISyntaxException {
UriInfo uriInfo = Mockito.mock(UriInfo.class);
Mockito.when(uriInfo.getRequestUri()).thenReturn(new URI(uri));
return uriInfo;
}


@Test
@DataSet({ "/datasets/object_target_type.xml", "/datasets/st_objective_levels.xml", "/datasets/st_objectives.xml", "/datasets/st_related_objectives.xml" })
@Transactional(TransactionMode.ROLLBACK)
public void testGetObjectives() throws Exception {
UriInfo uriInfo = mockUriInfo("http://localhost:8080/v1.0/objectives?planId=987&level=2");
Response response = restController.getObjectives(uriInfo);
Object objs = response.getEntity();

ReflectionAssert.assertLenientEquals(objs, Arrays.asList(
    new Objective(2L, "Obj1", new Level(2L), 987L, new TargetType(1L), 222d, 3),
    new Objective(3L, "Obj2", new Level(2L), 987L, new TargetType(1L), 333d, 3),
    new Objective(5L, "Obj5", new Level(2L), 987L, new TargetType(1L), 555d, 3),
    new Objective(6L, "Obj6", new Level(2L), 654L, new TargetType(1L), 666d, 3))
                    );

}

但是实际响应是一个StatusResponse,好像在RestController方法中抛出了一个异常。

我认为它无法模拟UriInfo,也没有看到QueryParams。

帮帮我,模拟UriInfo对象有什么错误

1 个答案:

答案 0 :(得分:1)

看起来你得到一个空指针异常,因为你没有模拟getQueryParameters()

你的模拟代码可能看起来像这样(为了清晰起见,我的内容有点简洁):

private UriInfo mockUriInfo(String uri) throws URISyntaxException {
    UriInfo uriInfo = Mockito.mock(UriInfo.class);
    URI uriObject = new URI(uri);
    Mockito.when(uriInfo.getRequestUri()).thenReturn(uriObject);
    Map<String,String> queryParametersMap = this.parseQueryParameters(uriObject.getQuery());
    Mockito.when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap(queryParametersMap));
    return uriInfo;
}

private Map<String,String> parseQueryParameters(String query) {
    String[] params = query.split("&");
    Map<String, String> map = new HashMap<String, String>();
    for (String param : params)
    {
        String[] pair = param.split("=");
        String name = pair[0];
        String value = pair[1];
        map.put(name, value);
    }
    return map;
}