有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一些关于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会被加载两次,每个测试类加载一次。由于它是在一个公共配置文件中定义的,有没有办法防止它多次加载


共 (1) 个答案

  1. # 1 楼答案

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

    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.

    如果这对你很重要,而且你愿意花时间,然后,您可以尝试实现一些基于以下事实的东西:应用程序上下文可以有一个父上下文(就像web应用程序中的两个上下文,一个为ContextLoaderListener定义,另一个为DispatcherServlet)定义),然后可能在不同的测试方法依赖的子上下文中使用/重用父上下文

    @SeeSpring Reference: Chapter 9.3.5.2 Context management and caching