Play framework 2.2.1: Create Http.Context for tests

安稳与你 提交于 2019-11-30 05:07:16

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);

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

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 verify if 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.*

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);
}

As a combination of the other answers:

In 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!