gpt4 book ai didi

java - JUnit:我可以保留 spring 上下文的公共(public)部分吗?

转载 作者:行者123 更新时间:2023-11-30 11:48:08 24 4
gpt4 key购买 nike

我对 Spring 进行了一些单元测试。所有测试都加载一个 spring 配置文件,然后再添加一些。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:beans.xml" }, inheritLocations = true)
public abstract class TestBase {
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:extraBeansOne.xml" }, inheritLocations = true)
public class TestOne extends TestBase {

@Test
public void testA() {
}
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:extraBeansTwo.xml" }, inheritLocations = true)
public class TestTwo extends TestBase {

@Test
public void testB() {
}
}

还有一个包含两个测试的套件:

@RunWith(Suite.class)
@Suite.SuiteClasses({ TestOne.class, TestTwo.class })
public class TestSuite {
}

在普通的spring配置文件中,我有一个bean:

<beans ...>
<bean id="testBean" class="com.example.TestBean" />
<bean>

问题是,当我运行该套件时,testBean 被加载两次,每个测试类加载一次。既然定义在一个普通的配置文件中,有什么办法可以防止它被多次加载?

最佳答案

不,真的没有机会重用它们。

Spring Junit Runner 在不同的测试中重用 spring 上下文,但前提是文件相同。

9.3.2.1 Context management and caching ...

Test classes provide an array containing the resource locations of XML configuration metadata - typically in the classpath - that is used to configure the application. These locations are the same as or similar to the list of configuration locations specified in web.xml or other deployment configuration files.

如果这对你来说非常重要并且你愿意花时间在上面,那么你可以尝试实现一些基于应用程序上下文可以有父级这一事实的东西(就像网络应用程序中的两个上下文,一个定义对于 ContextLoaderListener 另一个为 DispatcherServlet 定义的))然后可以在不同的测试方法依赖子上下文中使用/重用父上下文。

@见Spring Reference: Chapter 9.3.5.2 Context management and caching

关于java - JUnit:我可以保留 spring 上下文的公共(public)部分吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9005969/

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