Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

306
Views
How to Mock a service inside Controller Advice for Unit Testing

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")));
}
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!