gpt4 book ai didi

spring - 如何为多个测试类加载一次应用程序上下文

转载 作者:行者123 更新时间:2023-12-05 06:35:07 24 4
gpt4 key购买 nike

我有两个测试类

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 application Context。但是,我不想在两个类上都给 @RnWith(SpringRunner.class) & @ContextConfiguration(classes = {Config.class)}) 一次初始化应用程序上下文。同时我应该能够运行单个(通过 eclipse 的任何测试)测试。这可能吗。

经历了这个:test suite inside spring context .但它加载了应用程序上下文,但在 Test_1 或 Test_2 中不可用(gson 为空)。

最佳答案

Yes, this is perfectly possible. All you have to do is to use the same locations attribute in your test classes:

@ContextConfiguration(locations = "classpath:test-context.xml") Spring caches application contexts by locations attribute so if the same locations appears for the second time, Spring uses the same context rather than creating a new one.

I wrote an article about this feature: Speeding up Spring integration tests. Also it is described in details in Spring documentation: 9.3.2.1 Context management and caching.

This has an interesting implication. Because Spring does not know when JUnit is done, it caches all context forever and closes them using JVM shutdown hook. This behavior (especially when you have a lot of test classes with different locations) might lead to excessive memory usage, memory leaks, etc. Another advantage of caching context.

来源此answer

关于spring - 如何为多个测试类加载一次应用程序上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49839790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com