java - 在 Spring Boot 中模拟多个 bean

标签 java spring spring-boot testing mockito

我在 SpringBoot 中有一个测试应该以非常相同的方式检查多个 bean:

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class EndpointsTest implements ApplicationContextAware {

    @MockBean
    ComponentA componentA;
    @MockBean
    ComponentB componentB;

...

因为我不想为每个组件编写一个新的虚拟测试,所以我想获取所有 beans(因此使用 ApplicationContextAware),然后在每个这样的 bean 上运行测试。

当然,这些bean是要mock的。

有没有办法像 MockBean 注释那样手动模拟一个 bean 并将其替换为 Spring 上下文?我还想删除所有组件的显式声明(数量不小),只是为了模拟。

编辑:我想避免手动编写测试类中的所有组件。组件 bean 是按照约定命名的,所以我想获取它们,应用模拟并运行测试。我们有 100 多个组件。

最佳答案

我相信您已经尝试过显而易见的事情了吗?

@Configuration
@MockBeans({YourComponentSuperclass.class})
public class TestConfig {
}

如果这不起作用(例如因为@MockBean 期望单个匹配的 bean 进行装饰),您可以编写自己的 BeanFactoryPostProcessor,可能是受 Spring 自己的 MockitoPostProcessor(这使得 @MockBean 工作)。

关于java - 在 Spring Boot 中模拟多个 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57134567/

相关文章:

java - JasperReports Jackson 依赖冲突

Java内循环和外循环混淆?

html - Css 资源在 jsp 中不可用

java - 尽管未使用复合键,但仍收到错误 "Foreign key must have same number of columns as the referenced primary key"

spring - ModelMapper 与 Spring,在哪里放置显式映射?

java - 在 Spring Boot 应用程序的 REST 调用中接受 Enum 的空字符串

java - 我是否必须将一个类声明为公共(public)(它是程序中唯一没有人会使用的类)

java - 更改属性 View 中属性的顺序

spring-boot - 将属性值注入(inject) feignclient 注解

java - 尝试使用 Spring Security 自定义失败登录