title: How to Mock a service inside Controller Advice for Unit Testing
body: <p>The problem is I cannot unit test/mock this because the <strong>messageByLocaleService</strong> is null in the <strong>Controller Advice</strong>. Please suggest any way to inject the mock of messageByLocaleSerI have a set up like this:</p>
  
  <p><strong>ExceptionControllerAdvice class:</strong></p>
  
  <pre><code>@Autowired
  private MessageByLocaleService messageByLocaleService; //CANNOT MOCK THIS
  
  @ControllerAdvice
  public class ExceptionControllerAdvice {
  
      @ExceptionHandler(UserNotFoundException.class)
      public ResponseEntity&lt;String&gt; 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
      }
  }
  </code></pre>
  
  <p><strong>Controller method:</strong></p>
  
  <pre><code>@RequestMapping(value = "${foo.controller.requestMappingUrl.login}",
                                   method = RequestMethod.POST)
  public ResponseMessage&lt;String&gt; loginUser(
              @RequestParam("username") String username,
                 HttpServletRequest httpServletRequest,
                 HttpServletResponse httpServletResponse) throws Exception {
  
         return fooService.login(username);
  }
  </code></pre>
  
  <p><strong>JUnit setup &amp; test methods:</strong></p>
  
  <pre><code>@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?&amp;username=test")
                          .contentType(contentType)).
       andExpect(status().isNotAcceptable())
                  .andExpect(jsonPath("$.statusCode", is("ERRORCODE144")));
  }
  </code></pre>