spring 在单元测试中获得错误404而不是200

4c8rllxm  于 2022-12-21  发布在  Spring
关注(0)|答案(1)|浏览(95)

这是我的CurriculoControllerTest.java

@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("joao@email.com")
                        .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("joao@email.com")
                    .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());
    }

}

课程控制器.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);
}

课程服务实现

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;
}

我尝试了几十种不同的方法,但我总是得到404错误,即使我的URL是正确的,这可能是因为ID没有被找到?
java.lang.AssertionError:预期状态:<200>但实际状态:<404>预期:200实际:404

nnsrf1az

nnsrf1az1#

您模拟了CurriculoServiceImpl,但还没有stub service.findById(id)-您得到一个空的curriculo并返回HttpStatus.NOT_FOUND
顺便提一下-您似乎只测试了一个控制器来模拟它所依赖的服务-您可能需要考虑@WebMvcTest而不是@SpringBootTest

相关问题