2011-07-01 247 views
8

我有一個maven spring項目(最新版本),我想寫一些junit測試(最新版本)。spring junit測試

我遇到的問題是,我的spring beans是自動裝配的,當我從junit測試中調用它們時,我得到空指針異常,因爲spring沒有自動裝入它們。

如何加載上下文以使其自動裝配?

回答

21

您是否在Spring參考文檔中學習了Testing一章?下面是你應該開始一個例子:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration 
public class MyTest { 

    @Resource 
    private FooService fooService; 

    // class body... 
} 

如果你是在/src/test/javacom.example.MyTest,你將需要/src/test/resources/com/example/MyTest-context.xml - 但例外會告訴你的方式。

+1

+1 22秒:) – abalogh

+0

:-)我們的代碼片段我們可疑的相似,我聞到我們都用過的相同的參考;-)。 –

+0

http://static.springsource.org/spring/docs/3.0.x/reference/testing.html,難怪:) – abalogh

5

您應該在測試類中使用SpringJUnit4ClassRunner,並在包含該bean的測試類的字段上使用@Resource(或@Autowired)。您應該考慮使用特殊的測試環境Spring配置使用存根,以便您的測試是真正的單元測試,並且不依賴於整個應用程序上下文。

12

這是一個可能性:

@RunWith(SpringJUnit4ClassRunner.class) 
// ApplicationContext will be loaded from "/applicationContext.xml" 
// in the root of the classpath 
@ContextConfiguration({"/applicationContext.xml"}) 
public class MyTest { 
// class body... 
} 

通常這是一個好主意,但有一個測試的ApplicationContext爲您的測試基礎設施。