我在 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/