小编Jus*_*rds的帖子

依赖注入在Play Framework 2.4.x中的模型或测试中不起作用

我正在尝试为Play Framework 2.4.6应用程序编写一些单元测试.我需要WS用于我的目的测试.但是,当我使用documentmention的方法注入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
        });

    }
}
Run Code Online (Sandbox Code Playgroud)

这是运行激活器测试时的控制台输出

[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: …
Run Code Online (Sandbox Code Playgroud)

java unit-testing dependency-injection playframework

3
推荐指数
1
解决办法
1158
查看次数