【问题标题】:JUnit: Can I keep the common parts of the spring context?JUnit:我可以保留 spring 上下文的公共部分吗?
【发布时间】:2012-01-25 16:11:19
【问题描述】:

我对 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 被加载了两次,每个测试类加载一次。既然是在一个通用的配置文件中定义的,有什么办法可以防止它多次加载呢?

【问题讨论】:

  • 您在测试中实际在哪里使用“testBean”?
  • “被加载两次”是什么意思? Spring bean 默认是单例的,所以如果你有两个 testBean 实例,这意味着你有多个 Spring 上下文。
  • @isah,不管我是否使用 bean,它都会与上下文一起加载。
  • @Olaf,是的,第一个测试运行时加载一个上下文,第二个测试运行时加载另一个上下文;它们都在套件结束时被卸载,因此在第二次测试期间,我有两个“testBean” - 每个上下文中都有一个。问题是,我能否以某种方式重用上下文的公共部分,所以我只有一个“testBean”?
  • @Cosmin:正如 Ralph 回答的那样,您目前的方法无能为力。在我的单元测试中,我在类设置中加载上下文,如果我需要特定于测试的 bean,请在 Java 代码中手动注入它们。

标签: java spring junit


【解决方案1】:

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

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

9.3.2.1 Context management and caching ...

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

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

@见Spring Reference: Chapter 9.3.5.2 Context management and caching

【讨论】:

    猜你喜欢
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2016-06-17
    • 2016-02-02
    • 2018-03-29
    • 2016-10-07
    • 2019-01-29
    相关资源
    最近更新 更多