在每个春季启动 @Test 上覆盖单个 @Configuration 类

新手上路,请多包涵

在我的 Spring Boot 应用程序中,我只想用测试配置覆盖我的 @Configuration 类(特别是我的 @EnableAuthorizationServer @Configuration 类),全部测试。

到目前为止,在概述了 Spring Boot 测试特性Spring 集成测试特性 之后,还没有直接的解决方案浮出水面:

  • @TestConfiguration :用于扩展,而不是覆盖;
  • @ContextConfiguration(classes=…​)@SpringApplicationConfiguration(classes =…​) 让我覆盖整个配置,而不仅仅是一个类;
  • 建议在 --- 内部的 @Test @Configuration 类覆盖默认配置,但没有提供示例;

有什么建议么?

原文由 NotGaeL 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 495
1 个回答

内测配置

测试的内部 @Configuration 示例:

 @RunWith(SpringRunner.class)
@SpringBootTest
public class SomeTest {

    @Configuration
    static class ContextConfiguration {
        @Bean
        @Primary //may omit this if this is the only SomeBean defined/visible
        public SomeBean someBean () {
            return new SomeBean();
        }
    }

    @Autowired
    private SomeBean someBean;

    @Test
    public void testMethod() {
        // test
    }
}

可重用的测试配置

如果您希望为多个测试重用测试配置,您可以使用 Spring Profile @Profile("test") 定义一个独立的配置类。然后,让您的测试类使用 @ActiveProfiles("test") 激活配置文件。查看完整代码:

 @RunWith(SpringRunner.class)
@SpringBootTests
@ActiveProfiles("test")
public class SomeTest {

    @Autowired
    private SomeBean someBean;

    @Test
    public void testMethod() {
        // test
    }
}

@Configuration
@Profile("test")
public class TestConfiguration {
    @Bean
    @Primary //may omit this if this is the only SomeBean defined/visible
    public SomeBean someBean() {
        return new SomeBean();
    }
}

@基本的

bean 定义上的 @Primary 注释是为了确保如果找到多个,则该优先级。

原文由 alexbt 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题