2016-10-04 9 views
1

ワットコントローラクラスメソッドのユニットテスト私が注入された依存関係にプレイ:注射/

が含まれているコントローラクラスのメソッドのテストを記述しようとしているがこれは私のテストクラスの実装です:

public class MyTestClass { 
    private static Application app; 

    @BeforeClass 
    public static void beforeTest() { 
     app = Helpers.fakeApplication(Helpers.inMemoryDatabase()); 
     Helpers.start(app); 

     // ..... 
    } 

    @AfterClass 
    public static void afterTest() { 
     Helpers.stop(app); 
    } 

    @Test 
    public void testSomething() { 

     // ..... 
     app.injector().instanceOf(MyController.class).processSomething(); 

     // Some assertions here.. 
    } 

} 

MyController.processSomething()メソッドには、注入されたFormFactoryオブジェクトの使用に関するいくつかの実装が含まれています。

そして、私が実行しようとすると、私はnull

[error] Test MyTestClass.testSomething failed: null, took 0.137 sec 
[error] Failed: Total 1, Failed 1, Errors 0, Passed 0 
[error] Failed tests: 
[error]   MyTestClass 
[error] (test:test) sbt.TestsFailedException: Tests unsuccessful 


が質問取得します:どのように私は私がテストしてるコントローラはその注射を取得することがあることを確認していますか?

答えて

1

私は、アプリケーションライフサイクルを手動で処理する代わりに、WithApplicationからテストクラスを派生させることを提案します。これは次のようになります。

public class MyTestClass extends WithApplication { 
    @Test 
    public void testSomething() { 
     Helpers.running(Helpers.fakeApplication(),() -> { 
      // *whatever mocking* 
      RequestBuilder mockActionRequest = Helpers.fakeRequest(
             controllers.routes.MyController.processSomething()); 
      Result result = Helpers.route(mockActionRequest); 
      // *whatever assertions* 
     }); 
    } 
} 

さらに詳しい例はhereです。