The problem is I cannot unit test/mock this because the messageByLocaleService is null in the Controller Advice. Please suggest any way to inject the mock of messageByLocaleSerI have a set up like this:
ExceptionControllerAdvice class:
@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
}
}
Controller method:
@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 setup & test methods:
@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")));
}
It's a little hard to tell from the code that you've shown, but presumeably you are testing ExceptionControllerAdvice and create an instance somewhere in your Unit Test. If you do, try the following
@InjectMocks private ExceptionControllerAdvice unitUnderTest;
@Mock private MessageByLocaleService messageByLocaleService;
I believe that Mockito will create a Mock of the MessageByLocaleService and auto inject it into your ExceptionControllerAdvice.