[英]jUnit with Spring MVC always returns 400 on POST
我正在开发我的第一个带有后端和前端的 Spring 引导应用程序。 现在我正在为后端的 Controller 编写单元测试,以测试 Controller 响应代码。 我对 Controller 的测试 class 如下所示:
@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 class 中的代码如下所示:
@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);
}
}
问题是,一旦我运行测试,output 文件将显示此错误:
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() 覆盖了 function addHorse(),所以那里的验证永远不会发生,对吧? 所以我的猜测是,它以某种方式无法从测试 class 中的 Dto 创建有效的 JSON 以传递给 controller。 我已经查看了其他相关的 SO 问题,但似乎没有一个解决方案有效。 注意:我已经检查了测试 class 和 Dto class 中的日期类型是否一致。
我真的很感激任何帮助!
您的 controller 不知道您在测试中创建的horseService
。 您必须以某种方式注入 controller。
您可以在https://thepracticaldeveloper.com/guide-spring-boot-controller-tests/#mockitoextension-and-mockmvc上看到一些示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.