2016-10-04 28 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更多的例子。

相關問題