gpt4 book ai didi

spring-boot - 向 "@WebMvcTest"添加一个额外的 bean

转载 作者:行者123 更新时间:2023-12-03 13:44:32 25 4
gpt4 key购买 nike

我有一个 Controller 和一个使用 @WebMvcTest 的测试,它运行良好。现在我需要添加一些验证逻辑,为此我 @Autowired一个额外的 bean(一个 @Component ,一个 MapstructMapper)。

正如预期的那样,由于@WebMvcTest,测试失败了。 . (未发现任何组件)

有没有办法将一个 bean 添加到创建的上下文中?

由于我使用@MockBeans模拟服务层:有没有办法将所有模拟调用委托(delegate)给真实对象?有了这个我可以模拟映射器并委托(delegate)给真正的映射器?!

最佳答案

在上下文中获取附加 bean 的一种简单方法是在测试类中使用嵌套配置类

@TestConfiguration
static class AdditionalConfig {
@Bean
public SomeBean getSomeBean() {
return new SomeBean());
}
}

例子:

场景 - 如果你有一些 Controller 说 ProductController 并且你有相应的切片测试类说 ProductionControllerTest
@RestController
public class ProductController {

@Autowired
private IProductService productService;

@Autowired
private IProductValidator productValidator;


@GetMapping("product")
public Product getProduct(@RequestParam Long id) {

Product product = productService.getProduct(id); // you are using mockBean of productService

productValidator.validateProduct(product); // you need real bean of productValidator
return product;
}
}

带有附加 bean 配置的相应幻灯片测试类
@RunWith(SpringRunner.class)
@WebMvcTest
public class ProductControllerSliceTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private IProductService productService;

@Autowired
private ApplicationContext applicationContext;

@TestConfiguration
static class AdditionalConfig {
@Bean
public IProductValidator productValidator() {
return new ProductValidator();
}
}


@Test
public void testProductGetById() throws Exception {
Product testProductWithID1L = new Product(1L, "testProduct");
when(productService.getProduct(anyLong())).thenReturn(testProductWithID1L);

mockMvc.perform(get("/product")
.param("id", "1")).andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("name")
.value("testProduct"))
.andExpect(MockMvcResultMatchers.jsonPath("id")
.value("1"));
}
}

关于您的场景的其他想法:如果您真的打算对 Controller 类进行单元测试,那么理想情况下,您应该模拟您正在测试的类的所有其他依赖项。
理想情况下,单元测试的目的是只测试被测对象/类的行为。应该模拟所有依赖类的行为或外部调用。
当您开始在一个测试下一起测试多个类时,您将更多地转向组件测试或集成测试

关于spring-boot - 向 "@WebMvcTest"添加一个额外的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56021699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com