2016-01-21 124 views
2

我正在嘗試爲我的Play Framework 2.4.6應用程序編寫一些單元測試。我需要WS來進行我的目的測試。但是,當我使用文檔的方法來注入WS時,如果在測試或模型中使用了空指針,則最終會生成一個空指針。但是,如果我將其安裝到我的控制器之一,注射完美。依賴注入在模型或測試在Play Framework 2.4.x中不起作用

這裏是我的測試:

import org.junit.Test; 
import play.test.WithServer; 
import play.libs.ws.*; 
import javax.inject.Inject; 
import static play.test.Helpers.running; 
import static play.test.Helpers.testServer; 

public class UserProfileTests extends WithServer { 
    @Inject 
    WSClient ws; 

    @Test 
    public void demographicTest() { 

     System.out.println(ws.toString()); //null pointer exception 

     running(testServer(3333),() -> { 
      System.out.println(ws.toString()); //null pointer exception 
     }); 

    } 
} 

這裏是控制檯輸出運行激活測試時,

[error] Test UserProfileTests.demographicTest failed: java.lang.NullPointerException: null, took 5.291 sec 
[error]  at UserProfileTests.demographicTest(UserProfileTests.java:15) 
[error]  ... 
[error] Failed: Total 4, Failed 1, Errors 0, Passed 3 
[error] Failed tests: 
[error]  UserProfileTests 
[error] (test:test) sbt.TestsFailedException: Tests unsuccessful 
[error] Total time: 9 s, completed Jan 21, 2016 11:54:49 AM 

我敢肯定,我只是從根本上誤解一些有關依賴注入或系統如何作品。任何幫助將非常感激。

回答

5

由於測試應該只關注一個特定的scanario/object,所以我不認爲您需要擔心如何爲您的測試執行依賴注入,而只是實例化您需要的東西。這是一種使用應用程序Injector實例:

import org.junit.Before; 
import org.junit.Test; 
import play.libs.ws.WSClient; 
import play.test.WithServer; 

public class UserProfileTests extends WithServer { 

    private WSClient ws; 

    @Before 
    public void injectWs() { 
     ws = app.injector().instanceOf(WSClient.class); 
    } 

    @Test 
    public void demographicTest() { 
     System.out.println(ws); 
    } 
} 

但是,當然,你也可以只用手工實例化ws或者如果你想嘲笑它。

關於models,它們的生命週期不是由Guice處理的,因此在模型中沒有直接的方法進行依賴注入。你總是可以找到一個方法來做到這一點,但你應該?如果嘗試從數據庫加載100個對象,然後必須在每個對象中注入依賴項,會發生什麼?

除了(可能)的性能問題,也許你也在這裏違反Single Responsibility Principle,你的模型正在做很多工作。

+0

感謝您提供豐富的回覆。對此,我真的非常感激。 –