有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带有SpringMVC的JavaJUnit在POST上总是返回400

我正在用后端和前端开发我的第一个Spring Boot应用程序。现在,我正在为后端的控制器编写单元测试,以测试控制器响应代码。 控制器的测试类如下所示:

@WebMvcTest(controllers = HorseEndpoint.class)
@ActiveProfiles({"test", "datagen"})
public class HorseEndpointTest {

    @MockBean   //the dependencies the controller class needs
    private HorseService horseService;
    @MockBean
    private HorseMapper horseMapper;

    @Autowired
    private MockMvc mockMvc;
    @Autowired
    ObjectMapper objectMapper;

    Horse horseA = new Horse(-50L, "Pferd 1", null, new Date(0), Gender.MALE, null, null, null);

    @Test
    @DisplayName("Adding a valid horse should return the horse")
    public void addingHorse_valid_shouldReturnHorse() throws Exception {

        Mockito.when(horseService.addHorse(horseA)).thenReturn(horseA);

        mockMvc.perform(post("/horses")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(horseMapper.entityToDto(horseA)))
                .characterEncoding("utf-8"))
            .andExpect(status().is(201))
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.length()").value(1))
            .andDo(print());
    }
}

POST的控制器类中的代码如下所示:

@RestController
@RequestMapping("/horses")
public class HorseEndpoint {

    @PostMapping(value = "")
    @ResponseStatus(HttpStatus.CREATED)
    public HorseDto addHorse(@RequestBody HorseDto horseDto) {
        Horse horse = horseMapper.dtoToEntity(horseDto);
        try {
            horse = horseService.addHorse(horse);
        } catch (ValidationException v) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "The horse data provided is invalid: " + v.getMessage(), v);
        }
        return horseMapper.entityToDto(horse);
    }
}

问题是,只要我运行测试,输出文件就会显示以下错误:

Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 3.046 s <<< FAILURE! - in endpoint.HorseEndpointTest
addingHorse_valid_shouldReturnHorse  Time elapsed: 0.124 s  <<< FAILURE!
java.lang.AssertionError: Response status expected:<201> but was:<400>

请注意,从前端调用POST方法不会出现任何问题。类型为ValidationException的异常仅在服务层抛出,但我用Mockito重写了函数addHorse()。when(),所以验证永远不会发生,对吗? 因此,我猜测它无法从测试类中的Dto创建有效的JSON来传递给控制器。我已经看过其他相关的SO问题,但似乎没有一个解决方案有效。 注意:我已经检查了Test类和Dto类的日期类型是否一致

我真的很感激任何帮助


共 (1) 个答案