2011-12-14 333 views
54

我們有許多JUnit測試用例(集成測試),它們在邏輯上分組到不同的測試類中。在junit測試類中重複使用spring應用上下文

我們能夠爲每個測試類一旦加載Spring應用程序上下文,並在http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html

但提到重新使用它的所有測試用例在JUnit測試類,我們只是不知道是否有辦法爲一堆JUnit測試類加載Spring應用程序上下文一次。

FWIW,我們使用Spring 3.0.5,JUnit 4.5並使用Maven構建項目。

+0

以下所有的答案都是偉大的,但我沒有一個context.xml的。我注意到我的方式被遺忘了嗎?任何不使用context.xml的方法? – markthegrea 2018-02-07 21:12:44

回答

67

是的,這是完全可能的。所有你需要做的是使用相同的locations屬性,在測試類:由locations屬性

@ContextConfiguration(locations = "classpath:test-context.xml") 

春緩存應用程序上下文所以如果同一locations出現第二次,Spring使用同樣的背景下,而不是創建一個新的。

我寫了一篇關於此功能的文章:Speeding up Spring integration tests。另外它在Spring文檔中有詳細描述:9.3.2.1 Context management and caching

這有一個有趣的含義。因爲Spring不知道JUnit何時完成,所以它永遠緩存所有上下文並使用JVM關閉掛鉤關閉它們。這種行爲(尤其是當你有很多不同的測試類時)可能導致內存使用過多,內存泄漏等。緩存上下文的另一個優勢。

+0

啊!沒有意識到這一點。我們一直沿用這種方法很長一段時間,並且(錯誤地)將測試執行的持續時間歸因於每個測試類的春季上下文加載。現在仔細檢查。謝謝。 – Ramesh 2011-12-14 10:18:54

+0

我寧願說,那個春天並不瞭解你的測試用例的執行順序。由於這個原因,它不能分辨上下文是否需要,或者可以處置。 – philnate 2015-04-17 11:11:58

22

要添加到Tomasz Nurkiewicz's answer,自Spring 3.2.2開始@ContextHierarchy註釋可用於具有單獨的,關聯的多個上下文結構。當多個測試類想要共享(例如)內存數據庫設置(數據源,EntityManagerFactory,tx管理器等)時,這很有用。

例如:

@ContextHierarchy({ 
    @ContextConfiguration("/test-db-setup-context.xml"), 
    @ContextConfiguration("FirstTest-context.xml") 
}) 
@RunWith(SpringJUnit4ClassRunner.class) 
public class FirstTest { 
... 
} 

@ContextHierarchy({ 
    @ContextConfiguration("/test-db-setup-context.xml"), 
    @ContextConfiguration("SecondTest-context.xml") 
}) 
@RunWith(SpringJUnit4ClassRunner.class) 
public class SecondTest { 
... 
} 

有了這個設置一個使用「測試DB-設置-context.xml的」只會創建一次,但豆類裏面可以插入到各個單元測試的上下文背景

更多的手冊:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#testcontext-ctx-management(搜索「context hierarchy」)

相關問題