【发布时间】:2021-12-19 03:07:11
【问题描述】:
我正在为许多不同的 Spring 控制器编写端到端测试。现在,我正在尝试编写一个包含 MockMvc 执行方法的通用测试类。我有需要在不同控制器中调用的端点,我不想复制粘贴代码,并且在每个测试类中都有一个 MockMvc 和 ObjectMapper。
几个方法的例子:
public void saveMockDish(DishDto dishDto) throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.post(DISH_ENDPOINT)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(dishDto)))
.andExpect(status().isCreated());
}
public DishDto getMockDish(Long id) throws Exception {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders
.get(DISH_ENDPOINT + "/{id}", id))
.andExpect(status().isOk())
.andReturn();
String contentAsString = mvcResult.getResponse().getContentAsString();
return objectMapper.readValue(contentAsString, new TypeReference<>() {
});
}
我想要完成的事情(我可以在另一个类中自动装配的 bean,例如 DishControllerTest 类):
@AutoConfigureMockMvc
@TestComponent
public class AppMockMcv {
private static final String DISH_ENDPOINT = "/dishes";
private static final String BASE_INGREDIENTS_ENDPOINT = "/base-ingredients";
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
public List<DishDto> getMockDishes() throws Exception {
...
我想如何实例化我的测试类:
@SpringBootTest
public class DishControllerTest {
@Autowired
private AppMockMcv appMockMcv;
@Test
void testGetDishes() throws Exception {
List<DishDto> dishes = appMockMcv.getMockDishes();
assertEquals(4, dishes.size());
assertNotNull(dishes);
DishAssertions.containsDish(dishes, "Pasta Carbonara");
}
现在我面临无法将@AutoConfigureMockMvc 与@TestComponent 一起使用的问题,在自动装配中找不到bean。我还尝试了 AppMockMcv 类中的@Component、@TestConfiguration、@SpringBootTest 注解。
当前错误,虽然不是很有用:
No qualifying bean of type 'mtv.restaurant.mock.AppMockMcv' available:
expected at least 1bean which qualifies as autowire candidate.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)
我没有找到太多关于如何创建仅用于测试的 bean 以及如何将其与 AutoConfigureMockMvc 结合的信息。另外,我试图找到一种方法来扩展 MockMvc 却没有成功。
实现我想要实现的目标的正确方法是什么?
- 弹簧靴 2.5.4
【问题讨论】:
标签: java spring spring-boot spring-mvc spring-mvc-test