我正在嘗試爲我的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
我敢肯定,我只是從根本上誤解一些有關依賴注入或系統如何作品。任何幫助將非常感激。
感謝您提供豐富的回覆。對此,我真的非常感激。 –