如何为多个Test类加载应用程序上下文

时间:2018-04-15 08:07:19

标签: spring junit spring-test test-suite

我有两个测试类

public class Test_1 {

    @Autowired
    private Gson gson;

    @Test 
    public void test_1_1 () {
        assertNotNull(gson);
    }
}

public class Test_2 {

    @Autowired
    private Gson gson;

    @Test 
    public void test_2_1 () {
        assertNotNull(gson);
    }
}

两者都需要spring应用程序Context。但不是给@RnWith(SpringRunner.class)& @ContextConfiguration(classes = {Config.class)})在我想要初始化Application Context一次的类上。同时我应该能够运行单一(通过eclipse进行任何测试)测试。 这可能吗。

通过这个:test suite inside spring context。但它加载应用程序上下文但在Test_1或Test_2中不可用(gson为null)。

1 个答案:

答案 0 :(得分:0)

  

是的,这是完全可能的。你所要做的就是使用相同的东西   测试类中的locations属性:

     

@ContextConfiguration(locations =" classpath:test-context.xml")Spring   按位置属性缓存应用程序上下文,如果相同   位置第二次出现,Spring使用相同的上下文   而不是创建一个新的。

     

我写了一篇关于此功能的文章:加速Spring集成   试验。另外,它在Spring文档中有详细描述:   9.3.2.1上下文管理和缓存。

     

这有一个有趣的含义。因为春天不知道什么时候   JUnit完成后,它会永远缓存所有上下文并使用JVM关闭它们   关机钩。这种行为(特别是当你有很多测试时)   具有不同位置的类可能会导致过多的记忆   用法,内存泄漏等。缓存上下文的另一个好处。

来源answer

相关问题