Play Framework - Unit testing view templates

Trên play framework, chúng ta có thể viết unit test cho view templates theo như hướng dẫn từ trang play framework như sau: https://www.playframework.com/documentation/2.6.x/JavaTest

@Test
public void renderTemplate() {
    Content html = views.html.index.render("Welcome to Play!");
  assertEquals("text/html", html.contentType());
  assertTrue(contentAsString(html).contains("Welcome to Play!"));
}

Nhưng làm theo hướng dẫn này chúng ta sẽ gặp lỗi như sau:

[error] Test views.Errors_404Test.renderTemplate failed: java.lang.RuntimeException: There is no HTTP Context available from here., took 4.38 sec
[error]     at play.mvc.Http$Context.current(Http.java:68)
[error]     at play.mvc.Http$Context$Implicit.flash(Http.java:384)

Nguyên nhân của lỗi là do ta chưa set Context cho lớp HTTP.Context, fix bug trên như sau:

package views;

import org.junit.Before;
import play.Logger;
import play.api.mvc.RequestHeader;
import play.core.j.JavaContextComponents;
import play.mvc.Http;
import play.test.WithApplication;

import java.util.Collections;
import java.util.Map;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ViewTestBase extends WithApplication{
    @Before
    public void setUp(){
        Map<String, String> flashData = Collections.emptyMap();
        Map<String, Object> argData = Collections.emptyMap();
        Long id = 2L;
        RequestHeader header = mock(RequestHeader.class);
        Http.Request request = mock(Http.Request.class);
        final JavaContextComponents components = app.injector().instanceOf(JavaContextComponents.class);

        Http.Context context = new Http.Context(id, header, request, flashData, flashData, argData, components);
        Http.Context.current.set(context);
    }
}

Chuẩn bị class ViewTestBase, set current cho Http.Context, ở class Test kế thừa lại class ViewTestBase

package views;

import org.junit.Test;
import play.Logger;
import play.twirl.api.Content;

import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertTrue;
import static play.test.Helpers.contentAsString;

public class TemplateTest extends ViewTestBase {
    @Test
    public void renderTemplate() {
        Content html = views.html.index.render("Welcome to Play!");
        assertEquals("text/html", html.contentType());
        assertTrue(contentAsString(html).contains("Welcome to Play!"));
    }
}

All Rights Reserved