2011-07-01 13 views
8

私はmaven springプロジェクト(最新バージョン)を持っていて、いくつかのjunitテスト(最新バージョン)を書きたいと思っています。spring junit testing

私の春の豆はautowiredですが、私がjunitテストから呼び出すと、私は春がautowireしないので、nullポインタの例外を取得します。

コンテキストを読み込んで物事をオートワイヤードにするにはどうしたらいいですか?

答えて

21

春の参考資料でTestingの章を勉強しましたか?ここではあなたが開始する必要がある例:あなたは/src/test/javacom.example.MyTestしている場合

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

    @Resource 
    private FooService fooService; 

    // class body... 
} 

、あなたは/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を持っているかの良いアイデアです。