Java Play 框架 2.2.1:为测试创建 Http.Context

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20206270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:16:57  来源:igfitidea点击:

Play framework 2.2.1: Create Http.Context for tests

javaunit-testingplayframeworkplayframework-2.2

提问by Rico

I've been trying to create an Http.Context for tests using its constructor unsuccessfully. Does anybody see what I'm doing wrong?

我一直在尝试使用其构造函数为测试创建 Http.Context 失败。有没有人看到我做错了什么?

I've looked at the following but it only applies to Play 2.0:

我查看了以下内容,但它仅适用于 Play 2.0:

Play framework 2.0: Store values in Http.Context

Play 框架 2.0:在 Http.Context 中存储值

It looks like the class changed for 2.2.1 and it has more parameters for the constructor as shown here:

看起来这个类在 2.2.1 中发生了变化,并且它有更多的构造函数参数,如下所示:

https://github.com/playframework/playframework/blob/2.1.x/framework/src/play/src/main/java/play/mvc/Http.java

https://github.com/playframework/playframework/blob/2.1.x/framework/src/play/src/main/java/play/mvc/Http.java

This my code:

这是我的代码:

import java.util.Map;
import java.util.Collections;
import org.junit.*;
import static org.mockito.Mockito.*;
import play.mvc.*;
import play.test.*;
import play.mvc.Http;
import play.mvc.Http.Context;
import play.api.mvc.RequestHeader;
import static play.test.Helpers.*;
import static org.fest.assertions.Assertions.*;


public class TemplateTests {

    public static FakeApplication app;
    private final Http.Request request = mock(Http.Request.class);

    @BeforeClass
    public static void startApp() {
        app = Helpers.fakeApplication();
        Helpers.start(app);
    }

    @Before
    public void setUp() throws Exception {
        Map<String, String> flashData = Collections.emptyMap();
        Map<String, Object> argData = Collections.emptyMap();
        Long id = 2L;
        play.api.mvc.RequestHeader header = mock(play.api.mvc.RequestHeader.class);
        Http.Context context = mock(Http.Context(id, header, request , flashData, flashData, argData));
        Http.Context.current.set(context);
    }


    @Test
    public void renderTemplate() {
        Content html = views.html.index.render();
        assertThat(contentType(html)).isEqualTo("text/html");
        assertThat(contentAsString(html)).contains("myindex");
    }

    @AfterClass
    public static void stopApp() {
        Helpers.stop(app);
    }
}

This is the error that I'm seeing when running a test:

这是我在运行测试时看到的错误:

play test
[info] Loading project definition from /home/user/solr-segmentexplorer/explorer/project
[info] Set current project to explorer (in build file:/home/user/solr-segmentexplorer/explorer/)
[info] Compiling 1 Java source to /home/user/solr-segmentexplorer/explorer/target/scala-2.10/test-classes...
[error] /home/user/solr-segmentexplorer/explorer/test/TemplateTests.java:33: cannot find symbol
[error] symbol  : method Context(java.lang.Long,play.api.mvc.RequestHeader,play.mvc.Http.Request,java.util.Map<java.lang.String,java.lang.String>,java.util.Map<java.lang.String,java.lang.String>,java.util.Map<java.lang.String,java.lang.Object>)
[error] location: class play.mvc.Http
[error]         Http.Context context = mock(Http.Context(id, header, request , flashData, flashData, argData));
[error]                                         ^
[error] 1 error
[error] (test:compile) javac returned nonzero exit code
[error] Total time: 3 s, completed Nov 25, 2013 11:56:36 PM

Any ideas?

有任何想法吗?

If I don't create a context I get:

如果我不创建上下文,我会得到:

[error] Test TemplateTests.renderTemplate failed: java.lang.RuntimeException: There is no HTTP Context available from here.

[error] Test TemplateTests.renderTemplate failed: java.lang.RuntimeException: There is no HTTP Context available from here.

采纳答案by Rico

Looks like this seems to have fixed it for me:

看起来这似乎为我修复了它:

@Before
public void setUp() throws Exception {
    Map<String, String> flashData = Collections.emptyMap();
    Map<String, Object> argData = Collections.emptyMap();
    Long id = 2L;
    play.api.mvc.RequestHeader header = mock(play.api.mvc.RequestHeader.class);
    Http.Context context = new Http.Context(id, header, request, flashData, flashData, argData);
    Http.Context.current.set(context);
}

The part that fixes it specifically is:

具体修复它的部分是:

Http.Context.current.set(context);

回答by Blacklight

Just to provide an alternative using Mockito, only mocking just what you need (no manual instantiating of any class):

只是为了提供使用 Mockito 的替代方案,只模拟您需要的内容(无需手动实例化任何类):

private Http.Context getMockContext() {
    Http.Request mockRequest = mock(Http.Request.class);
    when(mockRequest.remoteAddress()).thenReturn("127.0.0.1");
    when(mockRequest.getHeader("User-Agent")).thenReturn("mocked user-agent");

    // ... and so on. Mock precisely what you need, then add it to your mocked Context

    Http.Context mockContext = mock(Http.Context.class);
    when(mockContext.request()).thenReturn(mockRequest);
    when(mockContext.lang()).thenReturn(Lang.forCode("en"));

    return mockContext;
}

You could also verifyif those fields have been used:

您还可以验证是否使用了这些字段:

@Test
public void testMockContext() {
    final Http.Context mockContext = getMockContext();

    assertThat(mockContext.request()).isNotNull();
    verify(mockContext).request();

    final String remoteAddress = mockContext.request().remoteAddress();
    assertThat(remoteAddress).isNotNull();
    assertThat(remoteAddress).isEqualTo("127.0.0.1");
    verify(mockContext.request()).remoteAddress();
}

Don't forget to import static org.mockito.Mockito.*

不要忘记 import static org.mockito.Mockito.*

回答by Rozuur

Just mocking context class solved the issue

只是嘲笑上下文类解决了这个问题

@Before
public void setUp() throws Exception {
    Http.Context context = mock(Http.Context.class);
    Http.Context.current.set(context);
}

回答by koppor

As a combination of the other answers:

作为其他答案的组合:

In build.sbt:

build.sbt

libraryDependencies += "org.mockito" % "mockito-core" % "1.10.19" % "test"

In your test class:

在您的测试课程中:

import play.mvc.Http;
import static org.mockito.Mockito.*;

@Before
public void setUp() throws Exception {
    Http.Context context = mock(Http.Context.class);
    Http.Flash flash = mock(Http.Flash.class);
    when(context.flash()).thenReturn(flash);
    Http.Context.current.set(context);
}

If you need more, just Mockito's functionalities. In case you are seeing any exceptions, just inspect the compiled code. IN my case, it was in target/scala-2.11/twirl/main/views/html/main.template.scala.

如果您需要更多,只需 Mockito 的功能即可。如果您看到任何异常,只需检查编译后的代码。就我而言,它在target/scala-2.11/twirl/main/views/html/main.template.scala.