Skip to content

Mockito is returning the incorrect response when testing a controller

I Have a misterius.

Im trying to write a Test for this controller Method:

public ResponseEntity<Object> getIncidencia(@PathVariable(value = "id") Long id){
   Optional<IncidenciaModel> incidenciaModelOptional = incidenciaService.findById(id);   
   if(!incidenciaModelOptional.isPresent()) {           
       return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Incidencia not found");           
   return ResponseEntity.status(HttpStatus.OK).body(incidenciaModelOptional.get());     

And I DID this:

public class IncidenciaControllerTest {

    private IncidenciaController controller;
    private IncidenciaService service;  
    private Optional<IncidenciaModel> incidenciaOptional;
    private static final Long ID = 1L;
    private static final Integer REGIAO_ID = 1;
    private static final Integer MES = 5;
    private static final Long FAIXA_ID = 2L;
    private static final Integer QNT_EXAME = 4;
    void setUp() {
    private void startIncidencia() {        
        incidenciaOptional = Optional.of(new IncidenciaModel(ID, REGIAO_ID, MES, FAIXA_ID, QNT_EXAME));
    void whenFindByIDThenReturnSuccess() {
        ResponseEntity<Object> response = controller.getIncidencia(ID);         
        //Assegure pra mim que o retorno não seja nulo.
        //Assegure pra mim que o corpo da resposta não pode ser null (porque tem que vir um userDTO).
        //Assegure pra mim que a resposta do endpoint vai ter a classe do tipo ResponseEntity
        Assertions.assertEquals(ResponseEntity.class, response.getClass());     
        //Assegure pra mim que eu ao encontrar o registro a resposta terá um Status Code 200 - OK.
        Assertions.assertEquals(HttpStatus.OK, response.getStatusCode());


I don’t know why but the method ResponseEntity<Object> response = controller.getIncidencia(ID); is returning <404 NOT_Found Not Found, Incidencia Not Found []> But the corret would be 200 OK. What I did Wrong?



I discovered but I do know why.

I re-wrote all the code, and when I took off the tag @CrossOrigin of the Controller my test run returned 200 OK. Does someone know why this occurred?

//@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {