为什么在Spring JUnit测试中为每个测试方法初始化并创建一个新的ApplicationContext?

时间:2015-04-24 12:27:04

标签: java spring junit applicationcontext spring-test

我正在春季学习单元测试,我有以下疑问。

为什么要为每个测试方法初始化和创建新的ApplicationContext?

为什么Spring需要为每个测试方法使用一个新的ApplicationContext,而不是重用在perfome任何方法之前创建的相同ApplicationContext?

2 个答案:

答案 0 :(得分:3)

  • 无需每次都创建新的ApplicationContext
  • 您必须在测试类中使用相同的locations属性:

    @ContextConfiguration(locations = "classpath:test-context.xml")
    
  • Spring按位置属性缓存应用程序上下文,因此如果第二次出现相同的位置,Spring会使用相同的上下文而不是创建新的上下文。

  • 您可以参考链接:NoBlogDefFound: Speeding up Spring integration tests

答案 1 :(得分:1)

这取决于您如何设置测试。如果您使用@SpringJUnit4ClassRunner@ContextConfiguration,那么Spring会缓存现有的ApplicationContext并重复使用它们。

您可以将上下文标记为脏,以防止重复使用。

如果您创建自己的ApplicationContext,则需要实施自己的重用/缓存策略。