Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JUnit:我可以保留spring上下文的公共部分吗?_Java_Spring_Junit - Fatal编程技术网

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

Java JUnit:我可以保留spring上下文的公共部分吗?,java,spring,junit,Java,Spring,Junit,我有一些Spring的单元测试。所有测试都加载一个spring配置文件,然后添加更多 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:beans.xml" }, inheritLocations = true) public abstract class TestBase { } @RunWith(SpringJUnit4ClassRunner.class) @Cont

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

没有,实际上没有机会重用它们

SpringJUnit运行程序在不同的测试中重用Spring上下文,但前提是文件相同

测试类提供一个数组,其中包含用于配置应用程序的XML配置元数据的资源位置(通常位于类路径中)。这些位置与web.xml或其他部署配置文件中指定的配置位置列表相同或相似

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


@请参见

您在测试中实际在哪里使用“testBean”?什么是“加载两次”?默认情况下,SpringBean是单例的,因此如果您有两个testBean实例,这意味着您有多个Spring上下文。@isah,无论我是否使用该bean,它都会随上下文一起加载。@Olaf,是的,第一个测试运行时会加载一个上下文,第二次测试运行时,另一次测试;它们都是在套件的末尾卸载的,所以在第二次测试中,我有两个“testBean”——每个上下文一个。问题是,我能否以某种方式重用上下文的公共部分,因此我只有一个“testBean”?@Cosmin:正如Ralph所回答的,您目前的方法无法做多少事情。在我的单元测试中,我在类设置中加载上下文,如果我需要特定于测试的bean,则将它们手动注入Java代码中。