2015-04-28 45 views
4

我想模擬一個服務,它從redis中獲取數據。我已經在新的上下文文件test-context.xml中的spring上下文中注入了bean。但是我有其他上下文文件A.xml,B。 xml在test-context.xml中參考beanS中的方法。我在enter link description here中閱讀了這個問題junit中的ContextConfiguration繼承

它創建了一個BaseTest類,但是當我繼承這個類時,我的上下文文件在子類中首先被加載,基類的上下文文件首先作爲子類上下文中的bean依賴於基類上下文。

@ContextConfiguration(locations = { "/META-INF/spring/testContext.xml" }) 
public abstract class myBaseTest { 
@Before 
public void init() { 
    // custom initialization code for resources loaded by testContext.xml 
} 

@After 
public void cleanup() { 
    // custom cleanup code for resources loaded by testContext.xml 
} 
} 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { "/META-INF/spring/A.xml", 
           "/META- INF/spring/B.xml" }) 
public class childTest extends myBaseTest { ... } 
+0

這不是你的問題的答案,但看看這篇文章,瞭解爲什麼不在測試系統中使用繼承http://www.petrikainulainen.net/programming/unit-testing/3-reasons-why-we -should - 不使用繼承功能於我們的測試/ – Vihar

回答

1

您可以簡單地將父上下文添加到子配置中。

@ContextConfiguration(locations = { "/META-INF/spring/testContext.xml", 
          "/META-INF/spring/A.xml", 
          "/META-INF/spring/B.xml"}) 

如果您不覆蓋它們,使用@Before和@After的方法將正常工作。