我有多个安全测试类,我在其中测试对不同 REST 端点的授权,我想模拟 ApplicationContext 将启动的所有存储库的 beans。我正在运行测试并且一切正常,但我不想在每个安全测试类中重复我的@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
关于java - Spring Boot @MockBeans - 如何在多个测试类中使用相同的 beans,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69903244/