【问题标题】:jUnit with Spring MVC always returns 400 on POST带有 Spring MVC 的 jUnit 在 POST 上总是返回 400
【发布时间】:2021-06-27 11:52:43
【问题描述】:

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

@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 的 Controller 类中的代码如下所示:

@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.when() 覆盖了函数 addHorse(),所以那里的验证永远不会发生,对吧? 所以我的猜测是它以某种方式无法从测试类中的 Dto 创建一个有效的 JSON 以传递给控制器​​。我已经查看了其他相关的 SO 问题,但似乎没有一个解决方案有效。 注意:我已经检查了 Test 类和 Dto 类的日期类型是否一致。

非常感谢任何帮助!

【问题讨论】:

    标签: java spring-boot junit mockito mockmvc


    【解决方案1】:

    您的控制器不知道您在测试中创建的模拟 horseService。您必须以某种方式注入控制器。

    您可以在 https://thepracticaldeveloper.com/guide-spring-boot-controller-tests/#mockitoextension-and-mockmvc 上查看有关如何执行此操作的一些示例

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 2020-04-01
    相关资源
    最近更新 更多