【问题标题】:DRY Spring AnnotationConfig testingDRY Spring 注解配置测试
【发布时间】:2013-07-30 21:08:20
【问题描述】:

所以,我正在做一些需要使用注解进行依赖注入的 Spring 测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class BeanTest {

  @Autowired
  private SomeService someService;

  @Configuration
  static class ContextConfiguration {
    @Bean
    public SomeService someService() {
        return new SomeService();
    }
  }
}

我真的不想在每次测试中都重复这段代码,但我尝试创建一个包含配置的基类:

@Configuration
class MyContextConfiguration {
   @Bean
   public SomeService someService() {
       return new SomeService();
   }
}

并从中派生:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class BeanTest {

  @Autowired
  private SomeService someService;

  @Configuration
  static class ContextConfiguration extends MyContextConfiguration {}
}

似乎不起作用。任何人都可以建议一种方法来干燥它吗?

谢谢!

【问题讨论】:

    标签: spring testing spring-test


    【解决方案1】:

    您应该可以这样做。

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    public class BeanTest {
    
      @Autowired
      private SomeService someService;
    
      @Configuration
      @Import(MyContextConfiguration.class)
      static class ContextConfiguration {
      ....
      }
    }
    

    另外,AnnotationConfigContextLoader 就不用提了,Spring 按照惯例会自动拾取带有@Configuration 注解的静态内部类,并使用合适的 ContextLoader

    【讨论】:

    • 看来@Import注解需要替换内部类和注解。如果您可以删除它,我可以接受...
    • 不是MyContextConfiguration,而是上面示例中的ContextConfiguration,并且由于这是导入MyContextConfiguration,因此其中的所有bean都应该在测试中可见..基本上任何带有注释的静态类@Configuraiton..这是一篇关于默认设置的小博客文章 - java-allandsundry.com/2012/08/…
    【解决方案2】:

    您可以在 contextconfiguration-annotation 中声明配置类。来自文档。

    上下文配置 定义用于确定如何为集成测试加载和配置 ApplicationContext 的类级元数据。具体来说,@ContextConfiguration 声明了应用程序上下文资源位置或将用于加载上下文的注释类。 资源位置通常是位于类路径中的 XML 配置文件;而带注释的类通常是 @Configuration 类。但是资源位置也可以引用文件系统中的文件,注解的类可以是组件类等。

    文档中的示例。

    @ContextConfiguration(classes = TestConfig.class)
    public class ConfigClassApplicationContextTests {
        // class body...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      • 2018-03-02
      相关资源
      最近更新 更多