LoginSignup
16

More than 5 years have passed since last update.

Play Framework (Java) の fakeApplication を使ったテストをスッキリ書く

Last updated at Posted at 2013-07-09

fakeApplication を使ったテストを普通に書くと長いですよね。

running(fakeApplication(), new Runnable() {
    public void run() {
        // ...
    }
});

そこで、こんなクラスを用意しておくと……

GreatFakeApp.java
import org.junit.rules.ExternalResource;

import play.test.FakeApplication;
import play.test.Helpers;

public class GreatFakeApp extends ExternalResource {
    private FakeApplication app;

    @Override
    protected void before() throws Throwable {
        app = Helpers.fakeApplication();
        Helpers.start(app);
    }

    @Override
    protected void after() {
        Helpers.stop(app);
    }
}

JUnit の @ClassRule を使ってテストをこのように書けます。

HogeTest
import static org.fest.assertions.Assertions.assertThat;
import static play.test.Helpers.*;

import org.junit.ClassRule;
import org.junit.Test;

public class HogehogeTest {

    @ClassRule public static GreatFakeApp app = new GreatFakeApp();

    @Test public void test() {
        Result result = fakeRequest(GET, "/");
        assertThat(status(result)).isEqualTo(OK);
    }

}

スッキリ!

この場合は @BeforeClass のように、テストクラスごとに fakeApplication が作られます。

参考:

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16