在每次春季启动时都覆盖一个@Configuration类@Test

Not*_*aeL 43 spring spring-test spring-boot

在我的春季启动应用程序中,我希望@Configuration在我的@EnableAuthorizationServer @Configuration所有测试中仅使用测试配置(特别是我的类)覆盖我的一个类.

到目前为止,在概述了弹簧启动测试功能弹簧集成测试功能之后,没有出现直接的解决方案:

  • @TestConfiguration:这是为了扩展,而不是超越;
  • @ContextConfiguration(classes=…?)@SpringApplicationConfiguration(classes =…?)让我覆盖整个配置,而不仅仅是一个类;
  • 建议@Configuration在a 内部的类@Test覆盖默认配置,但不提供示例;

有什么建议?

ale*_*xbt 59

内部测试配置

测试的内部@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
    }
}
Run Code Online (Sandbox Code Playgroud)

可重复使用的测试配置

如果您希望将测试配置重用于多个测试,则可以使用Spring配置文件定义独立的Configuration类@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

@主

@Primarybean定义的注释是为了确保如果找到多个,那么这个注释将具有优先级.

  • 如果其中一个bean在内部使用,它是由SomeBean类注入的,那么你的解决方案就会失败.为了使其工作,只需在SpringBootTest注释使用的类列表中添加ContextConfiguration类.那就是:@SpringBootTest(classes = {Application.class,SomeTest.ContextConfiguration.class}) (11认同)
  • "可重用"部分不起作用.在我的例子中,尽管在test-config中将@Primary放在bean上,Spring仍然使用main-config中的bean覆盖它.即它覆盖,只是不是你期望的方式 - 选择错误的bean. (4认同)
  • 谢谢.我注意到我也可以通过在`src/test/java`上删除重写的`@EnableAuthorizationServer`` @ Configuration`类来覆盖所有测试中的类.春季启动规则:-) (2认同)

Sla*_*bin 11

您应该使用spring boot配置文件:

  1. 使用注释来标记您的测试配置@Profile("test").
  2. 使用标注您的生产配置@Profile("production").
  3. 在属性文件中设置生产配置文件:spring.profiles.active=production.
  4. 使用在测试类中设置测试配置文件@Profile("test").

因此,当您的应用程序启动时,它将使用"生产"类,当测试星星时它将使用"测试"类.

如果使用内部/嵌套@Configuration类,则将使用它而不是应用程序的主要配置.