anyString()什么时候使用
1.1).比如在controller层,API地址中有映射参数时,那么when的时候(模拟service层调用)就要用到anyString()
eg:
Controller Layer:
@DeleteMapping(value = "/detail/lock/{guid}")
@ApiOperation(value = "delete the lock ", notes = "delete the lock.", response =EntlMappingDetailInfoDtoResponse.class)
public ResponseEntity<ApiMessage<Object>> deleteObjectLock(@PathVariable String guid) {
return new ResponseEntity<>(entitlementMappingService.releaseEntitlementMappingLock(guid, CommonConstants.OBJECT_LOCK_TYPE), HttpStatus.OK);
}
Junit Test for Controller Layer:
@Test
public void testDeleteObjectLock() throws UnsupportedEncodingException, Exception
{
String requestURI = "/detail/lock/test";
ApiMessage<Object> message = MessageUtil.getSuccessMessage(anyString());
when(entlMappingService.releaseEntitlementMappingLock(anyString(), CommonConstants.OBJECT_LOCK_TYPE)).thenReturn(message);
String response = mockMvc.perform(delete(requestURI)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertNotNull(response);
}
1.2)这里releaseEntitlementMappingLock(argu1,argu2)方法第一个参数由于是从API地址传过来的,所以需要用到anyString()
Controller层delete方法参数是String[]
2.1)eg:
@DeleteMapping(value = "/entitlementmapping")
public ResponseEntity<ApiMessage<Object>> deleteEntitlementMapping(@RequestBody String[] guids) {
return new ResponseEntity<>(entitlementMappingService.deleteEntitlementMapping(guids), HttpStatus.OK);
}
2.2)那么单元测试就应该这样写:
@Test
public void testDeleteEntitlementMapping() throws UnsupportedEncodingException, Exception
{
String requestURI = "/entlmapping/entitlementmapping";
String[] array = { "test" };
JSONArray jsonArray = JSONArray.fromObject(array);
String requestBody = jsonArray.toString();
ApiMessage<Object> message = MessageUtil.getSuccessMessage(anyString());
when(entlMappingService.deleteEntitlementMapping(array)).thenReturn(message);
String response = mockMvc.perform(delete(requestURI).contentType(MediaType.APPLICATION_JSON).content(requestBody))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertNotNull(response);
}
多层mock问题如何处理
3.1)遇到多层mock问题这样mock,eg:
userId = String.valueOf(httpServletRequest.getSession().getAttribute(CommonConstants.OBJECT_LOCK_USER_ID_KEY));
3.2)思路,先mock:when(httpServletRequest.getSession()).thenReturn(XXX)这个,接下来再mock:
XXX.getAttribute();
3.3)当然这些httpServletRequest需要作为全局变量进行mock
@Mock
private HttpServletRequest request;
@Mock
private HttpSession session;
when(request.getSession()).thenReturn(session);
这样就不会出现空指针异常