【发布时间】:2016-01-21 18:56:32
【问题描述】:
我正在尝试为我的 Play Framework 2.4.6 应用程序编写一些单元测试。我需要 WS 用于我的目的测试。但是,当我使用文档的方法注入 WS 时,如果在测试或模型中使用,我最终会得到一个空指针。但是,如果我将它安装到我的一个控制器中,注入会完美运行。
这是我的测试:
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
我确定我只是从根本上误解了有关依赖注入或系统工作原理的一些东西。任何帮助将不胜感激。
【问题讨论】:
标签: java unit-testing playframework dependency-injection