【发布时间】:2017-03-29 07:12:46
【问题描述】:
问题是我无法对它进行单元测试/模拟,因为 messageByLocaleService 在 Controller Advice 中为空。请提出任何注入 messageByLocaleSer 模拟的方法我有这样的设置:
ExceptionControllerAdvice 类:
@Autowired
private MessageByLocaleService messageByLocaleService; //CANNOT MOCK THIS
@ControllerAdvice
public class ExceptionControllerAdvice {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUnexpectedException(HttpServletRequest request, Exception e) {
//build response as below
String s = messageByLocaleService.buildMessage(HttpStatus.ERROR,"User Not Valid"); // GETTING NULL HERE
//and send the response back to the client here
}
}
控制器方法:
@RequestMapping(value = "${foo.controller.requestMappingUrl.login}",
method = RequestMethod.POST)
public ResponseMessage<String> loginUser(
@RequestParam("username") String username,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws Exception {
return fooService.login(username);
}
JUnit 设置和测试方法:
@InjectMocks
private ProjectController projectController;
@Mock
private FooService fooService;
@Mock
private MessageByLocaleService messageByLocaleService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(projectController)
.setMessageConverters(new MappingJackson2HttpMessageConverter())
.setControllerAdvice(new ExceptionControllerAdvice()).build();
}
@SuppressWarnings("unchecked")
@Test
public void testControllerUserNotFoundException() throws Exception {
Response resp = new Response();
resp.setStatusCode(StatusCode.UserNotFoundErrorCode);
when(fooService.login(any(String.class)).
thenThrow(UserNotFoundException.class);
mockMvc.perform(post("/service-user/1.0/auth/login?&username=test")
.contentType(contentType)).
andExpect(status().isNotAcceptable())
.andExpect(jsonPath("$.statusCode", is("ERRORCODE144")));
}
【问题讨论】:
标签: java spring spring-mvc mockito spring-test