Skip to content
Advertisement

Mockito is returning the incorrect response when testing a controller

I Have a misterius.

Im trying to write a Test for this controller Method:

@GetMapping("/{id}")    
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:

@SpringBootTest
public class IncidenciaControllerTest {

    @InjectMocks
    private IncidenciaController controller;
    
    @Mock
    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;
    
    @BeforeEach
    void setUp() {
        startIncidencia();
        MockitoAnnotations.openMocks(this);
    }
    
    private void startIncidencia() {        
        incidenciaOptional = Optional.of(new IncidenciaModel(ID, REGIAO_ID, MES, FAIXA_ID, QNT_EXAME));
    }   
    
    @Test
    void whenFindByIDThenReturnSuccess() {
        Mockito.when(service.findById(Mockito.anyLong())).thenReturn(incidenciaOptional);       
        ResponseEntity<Object> response = controller.getIncidencia(ID);         
        //Assegure pra mim que o retorno não seja nulo.
        Assertions.assertNotNull(response);
        //Assegure pra mim que o corpo da resposta não pode ser null (porque tem que vir um userDTO).
        Assertions.assertNotNull(response.getBody());
        //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?

Advertisement

Answer

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?

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