首页 > 解决方案 > Spring Boot @MockBeans - 如何在多个测试类中使用相同的 bean

问题描述

我有多个安全测试类,我正在测试对不同 REST 端点的授权,并且我想模拟 ApplicationContext 将启动的所有存储库的 bean。我正在运行测试并且一切正常,但我不想在每个安全测试类中复制我的@MockBeans。

我尝试创建一个配置类并将 MockBeans 放在那里,但收到 404 错误。

当前的测试类是这样设置的,它可以工作,但我必须在每个类中复制 @MockBeans() :

@WebMvcTest(value = [ScriptController, SecurityConfiguration, ScriptPermissionEvaluator])
@ExtendWith(SpringExtension)
@MockBeans([@MockBean(ObjectRepository), @MockBean(ChannelRepository), 
@MockBean(ChannelSubscriberRepository)])
@ActiveProfiles("test")
class ScriptControllerSecurityTest extends Specification

我想设置一个这样的配置类,并在测试类中使用 @ContextConfiguration(classes = MockRepositoryConfiguration) 在我的测试类中使用它。

@Configuration
@MockBeans([@MockBean(ObjectRepository), @MockBean(ChannelRepository), 
@MockBean(ChannelSubscriberRepository)])
class MockRepositoryConfiguration
{}

标签: javaspringspring-bootspring-mvcspring-bean

解决方案


尝试按如下方式创建自定义元注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.Type)
@MockBeans([@MockBean(ObjectRepository), @MockBean(ChannelRepository), 
@MockBean(ChannelSubscriberRepository)])
public @interface CustomMockBeans {
}

然后用它注释你的测试类:

@WebMvcTest(value = [ScriptController, SecurityConfiguration, ScriptPermissionEvaluator])
@ExtendWith(SpringExtension)
@CustomMockBeans
@ActiveProfiles("test")
class ScriptControllerSecurityTest extends Specification

推荐阅读