Play framework 2.2.1: Create Http.Context for tests

后端 未结 4 1391
半阙折子戏
半阙折子戏 2020-12-29 10:35

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

I\'ve looked at the following but

4条回答
  •  -上瘾入骨i
    2020-12-29 11:03

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

提交回复
热议问题