【问题标题】:Best way to exclude unit test @Configurations in Spring?在 Spring 中排除单元测试 @Configurations 的最佳方法?
【发布时间】:2015-12-23 17:04:10
【问题描述】:

在我的 Spring Boot 项目中,我有一个用 @SpringBootConfiguration 注释的主类。我还有一些使用@SpringApplicationConfiguration 的单元测试,它指向一个内部类,该内部类定义了一个Spring 上下文以在我的单元测试中使用(使用一些模拟)。

我现在想编写一个集成测试来启动我的应用程序的完整上下文。但是,这不起作用,因为它还会获取在其他单元测试中定义为内部类的 Spring 上下文。

避免这种情况的最佳方法是什么?我确实在@SpringBootConfiguration 上看到了excludeexcludeName 属性,但我不确定如何使用它们。

更新:

更多解释问题的代码:

我的主要课程:

package com.company.myapp;

@SpringBootApplication
@EnableJpaRepositories
@EnableTransactionManagement
@EntityScan(basePackageClasses = {MyApplication.class, Jsr310JpaConverters.class})
public class MyApplication {
  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
  }
}

我对 Spring REST Docs 进行了单元测试:

package com.company.myapp.controller

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration
@WebAppConfiguration
public class SomeControllerDocumentation {

@Rule
public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");

  // Some test methods here


  // Inner class that defines the context for the unit test
  public static class TestConfiguration {
    @Bean
    public SomeController someController() { return new SomeController(); }

    @Bean
    public SomeService someService() { return new SomeServiceImpl(); }

    @Bean
    public SomeRepository someRepository() { return mock(SomeRepository.class);
}

所以单元测试使用内部类中定义的上下文。现在我想要一个不同的测试来测试应用程序的“正常”应用程序上下文是否启动:

package com.company.myapp;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MyApplication.class)
@WebAppConfiguration
public class MyApplicationTest {

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void whenApplicationStarts_thenContextIsInitialized() {
        assertThat(applicationContext).isNotNull();
    }

}

这个测试现在不仅会连接它应该连接的东西,还会连接来自 SomeControllerDocumentation.TestConfiguration 内部类的 bean。这是我想避免的。

【问题讨论】:

    标签: java spring unit-testing spring-boot


    【解决方案1】:

    您可以使用配置文件:使用@Profile("unit-test")@Profile("integration-test") 注释相关的配置bean,并在测试中通过@ActiveProfiles 指定应该激活哪个配置文件。

    不过,听起来您只需重新组织配置结构就可以完全避免该问题。但是,如果没有看到任何代码,就很难假设任何事情。

    【讨论】:

      【解决方案2】:

      从 Spring Boot 1.4 开始,可以通过在单元测试中使用 @TestConfiguration 注释配置来避免该问题

      【讨论】:

        【解决方案3】:

        我觉得你说的是@Ignore

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-23
          • 1970-01-01
          • 2018-02-20
          • 2011-02-24
          • 2010-09-08
          相关资源
          最近更新 更多