在Spring中排除单元测试@Configurations的最佳方法是什么?

3
在我的Spring Boot项目中,我有一个被注解为@SpringBootConfiguration的主类。我还有一些单元测试使用了@SpringApplicationConfiguration,指向定义了Spring上下文以供在我的单元测试中使用(使用一些模拟)的内部类。
现在我想编写一个集成测试来启动应用程序的完整上下文。但是,这样做无法正常工作,因为它还会捕获其他单元测试中定义的内部类的Spring上下文。
如何避免这种情况呢?我看到了@SpringBootConfigurationexcludeexcludeName属性,但我不确定如何使用它们。
更新:
一些代码来更好地说明问题:
我的主类:
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内部类的beans。我希望避免这种情况。

3个回答

3
你可以使用配置文件:在相关的配置bean上注释@Profile("unit-test")@Profile("integration-test"),在测试中通过@ActiveProfiles指定哪个配置文件应该被激活。
然而,如果重新组织你的配置结构,似乎可以完全避免这个问题。不过,没有看到任何代码就很难做出任何假设。

1

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


-2

我认为你在谈论 @Ignore


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接