繁体   English   中英

Spring Boot @MockBeans - 如何在多个测试类中使用相同的 bean

[英]Spring Boot @MockBeans - How to use the same beans in multiple test classes

我有多个安全测试类,我在其中测试对不同 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
{}

尝试创建自定义元注释,如下所示:

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM