Home > Back-end >  Getting error 404 instead of 200 in unit test
Getting error 404 instead of 200 in unit test

Time:12-20

This is my CurriculoControllerTest.java class

@SpringBootTest
@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@DisplayName("Curriculo Controller Test")
@ActiveProfiles("local")
@AutoConfigureMockMvc
@Import(CurriculoController.class)
class CurriculoControllerTest {

    private final String JSON_FORMAT = "application/json; charset=utf-8";
    private final String BASE_PATH = "/curriculos";

    @MockBean
    private CurriculoServiceImpl curriculoService;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private MockMvc mockMvc;

    public static CurriculoDTO createCurriculoInput() {
        return CurriculoDTO.builder()
                .id(UUID.randomUUID())
                .dadosPessoais(DadosPessoaisDTO.builder()
                        .nome("joão")
                        .cargo("programador")
                        .email("[email protected]")
                        .build())
                .build();
    }

    CurriculoDTO novoCurriculo = CurriculoDTO.builder()
            .id(UUID.randomUUID())
            .dadosPessoais(DadosPessoaisDTO.builder()
                    .nome("Bruno")
                    .build())
            .build();

    CurriculoDTO curriculoExpected = CurriculoDTO.builder()
            .id(UUID.randomUUID())
            .dadosPessoais(DadosPessoaisDTO.builder()
                    .nome("Bruno")
                    .cargo("programador")
                    .email("[email protected]")
                    .build())
            .build();

    @Test
    @DisplayName("Deve retornar sucesso ao atualizar os dados pessoais do currículo")
    public void deveRetornarSucessoAoAtualizarDadosPessoaisDoCurriculo() throws Exception {
        var ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        var json = ow.writeValueAsString(curriculoExpected.getDadosPessoais());
        doReturn(curriculoExpected).when(curriculoService)
                .updateDadosPessoais(createCurriculoInput().getDadosPessoais(), novoCurriculo.getId());
        mockMvc.perform(patch(BASE_PATH   "/dados-pessoais/"   createCurriculoInput().getId()).contentType(JSON_FORMAT).content(json))
                .andExpect(status().isOk());
    }

}

CurriculoController.java

@RestController
@RequestMapping("/curriculos")
public class CurriculoController {

private final DateTimeFormatter YYYY_MM_DD = DateTimeFormatter.ofPattern("yyyy-MM-dd");

private final CurriculoServiceImpl service;

@Autowired
public CurriculoController(CurriculoServiceImpl service) {
    this.service = service;
}

@PatchMapping("/dados-pessoais/{id}")
public ResponseEntity<CurriculoDTO> updateDadosPessoais(@RequestBody @Valid DadosPessoaisDTO dto,
                                                        @PathVariable UUID id) {
   Optional<CurriculoDTO> curriculo = Optional.ofNullable(service.findById(id));
   if (curriculo.isEmpty()) {
       return new ResponseEntity<>(HttpStatus.NOT_FOUND);
   }
   return new ResponseEntity<>(service.updateDadosPessoais(dto, id), HttpStatus.OK);
}

CurriculoServiceImpl

public CurriculoDTO updateDadosPessoais(DadosPessoaisDTO dto, UUID id) {
    Optional<Curriculo> optCurriculo = repository.findById(id)
            .map(curriculo -> {
                curriculo.setNome(Objects.nonNull(dto.getNome())
                        ? dto.getNome() : curriculo.getNome());
                curriculo.setCargo(Objects.nonNull(dto.getCargo())
                        ? dto.getCargo() : curriculo.getCargo());
                curriculo.setEmail(Objects.nonNull(dto.getEmail())
                        ? dto.getEmail() : curriculo.getEmail());
                curriculo.setSumario(Objects.nonNull(dto.getSumario())
                        ? dto.getSumario() : curriculo.getSumario());
                curriculo.setLinguagem(Objects.nonNull(dto.getLinguagem())
                        ? dto.getLinguagem() : curriculo.getLinguagem());
                return repository.save(curriculo);
            });
    CurriculoDTO curriculoDTO = converter.mapCurriculoToCurriculoDTO(optCurriculo.orElse(null));
    curriculoDTO.setDadosPessoais(dto);
    return curriculoDTO;
}

I've tried dozens of different ways, but I keep getting the 404 error, even though my URL is correct, could it be because the ID is not being found?

java.lang.AssertionError: Status expected:<200> but was:<404> Expected :200 Actual :404

CodePudding user response:

You mocked CurriculoServiceImpl but haven't stubbed service.findById(id) - you get an empty curriculo and return HttpStatus.NOT_FOUND.

As a side note - you seem to be testing only one controller mocking a service it depends on - you may want to consider @WebMvcTest instead of @SpringBootTest

  • Related