所以我开始为我们的项目编写Junit测试,我们正在使用Junit和Mockito。但是,当我尝试测试REST端点(通过Jersey实现)时,测试通过但我仍然获得该方法的0%覆盖率
这是代码
@GET
@Path("/{workFlow}/{caseId}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public ResponseObject caseManagementGet(@Context UriInfo context, @PathParam("workFlow") String workFlow,
@PathParam("caseId") String caseId, @QueryParam("details") String details) throws ApiException {
QueryParameters queryParameters = new QueryParameters();
PathParameters pathParameters = new PathParameters();
buildPathParameter(pathParameters, ParameterName.workflow, workFlow);
buildPathParameter(pathParameters, ParameterName.id, caseId);
buildQueryParameter(queryParameters, ParameterName.details, details);
return invokeHandler(context.getPath(), workFlow, RETRIEVE_CASE_DETAIL_ACTION, HttpMethod.GET, pathParameters,
queryParameters, null);
}
protected void buildPathParameter(PathParameters pathParameters, ParameterName name, Object value)
throws ApiException {
try {
pathParameters.put(name, value);
return;
}
catch (ParameterException e) {
throw apiException(DXM_UNSUPPORTED_SERVICE_ERROR, e);
}
catch (Exception e) {
throw apiException(DXM_GENERAL_ERROR, e);
}
}
protected void buildQueryParameter(QueryParameters queryParameters, ParameterName name, Object value)
throws ApiException {
try {
queryParameters.put(name, value);
return;
}
catch (ParameterException e) {
throw apiException(DXM_UNSUPPORTED_SERVICE_ERROR, e);
}
catch (Exception e) {
throw apiException(DXM_GENERAL_ERROR, e);
}
}
这是Junit测试
@InjectMocks
@Spy
CaseManagementResource caseManagementResource = new CaseManagementResource();
@Mock
RequestObject requestObject;
@Mock
ResponseObject responseObject;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCaseManagementGet() throws ApiException, URISyntaxException {
try{
UriInfo uriInfo = Mockito.mock(UriInfo.class);
Mockito.when(uriInfo.getAbsolutePath())
.thenReturn(URI.create("http://localhost:8080/bbpro/rest/v1/get"));
ResponseObject response = caseManagementResource.caseManagementGet(uriInfo, "bbc", "123123", "setup");
Assert.assertNotNull(response);
}catch(ApiException e){
e.getMessage();
}
}

我将模拟值传递给GET方法,然后断言不为null。