문제는 messageByLocaleService가 컨트롤러 조언의 null 때문에 내가하지 단위 테스트 /이 조롱 할 수 있습니다에 대한 컨트롤러 조언 내부의 서비스를 모의한다. messageByLocaleSerI의 모의를 주입 할 수있는 방법을 제안 해주십시오 것은 다음과 같이 설정 한 :어떻게 단위 테스트
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")));
}
내 단위 테스트 클래스에서 이것을 추가했습니다. 제안 해 주셔서 감사합니다. – nanospeck