在每个spring boot @Test上重写单个@Configuration类 [英] Override a single @Configuration class on every spring boot @Test

查看:335
本文介绍了在每个spring boot @Test上重写单个@Configuration类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的spring boot应用程序上,我想在所有测试中仅使用测试配置覆盖我的@Configuration类之一(特别是我的@EnableAuthorizationServer @Configuration类).

On my spring boot application I want to override just one of my @Configuration classes with a test configuration (in particular my @EnableAuthorizationServer @Configuration class), on all of my tests.

到目前为止,概述了 Spring Boot测试功能

So far after an overview of spring boot testing features and spring integration testing features no straightforward solution has surfaced:

  • @TestConfiguration:用于扩展,而不是覆盖;
  • @ContextConfiguration(classes=…​)@SpringApplicationConfiguration(classes =…​)让我覆盖整个配置,而不仅仅是一个类;
  • 建议在@Test中使用内部的@Configuration类覆盖默认配置,但未提供示例;
  • @TestConfiguration: It's for extending, not overriding;
  • @ContextConfiguration(classes=…​) and @SpringApplicationConfiguration(classes =…​) let me override the whole config, not just the one class;
  • An inner @Configuration class inside a @Test is suggested to override the default configuration, but no example is provided;

有什么建议吗?

推荐答案

内部测试配置

用于测试的内部@Configuration的示例:

Example of an inner @Configuration for your test:

@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")定义一个独立的Configuration类.然后,让您的测试班级使用@ActiveProfiles("test")激活配置文件.查看完整的代码:

If you wish to reuse the Test Configuration for multiple tests, you may define a standalone Configuration class with a Spring Profile @Profile("test"). Then, have your test class activate the profile with @ActiveProfiles("test"). See complete code:

@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();
    }
}

@Primary

bean定义上的@Primary批注是为了确保如果找到一个以上,则该优先级高.

The @Primary annotation on the bean definition is to ensure that this one will have priority if more than one are found.

这篇关于在每个spring boot @Test上重写单个@Configuration类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆