Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

309
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda