LoginSignup
17
15

More than 5 years have passed since last update.

Jerseyのテスト(JerseyTest)をJUnit4のRuleで動かす

Posted at

Jersey のテストを書こうと思ったら、 JerseyTest を継承するって ユーザーガイドに書いてあった

JUnit4 使うんだったら、やっぱり @Rule で書いたほうがスタイリッシュなので、 @Rule で動かせるか試してみた。

GitHub でサンプルを公開してます

リソースクラス

SampleResource.java
package sample.jersey;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("sample")
public class SampleResource {

    @GET
    public String method() {
        return "sample resource";
    }
}

ルールクラス

JerseyTestRule.java
package sample.jersey;

import javax.ws.rs.core.Application;

import org.glassfish.jersey.test.JerseyTest;
import org.junit.rules.ExternalResource;

public class JerseyTestRule extends ExternalResource {

    private JerseyTest jerseyTest;

    public JerseyTestRule(final Application config) {
        this.jerseyTest = new JerseyTest() {
            @Override
            protected Application configure() {
                return config;
            }
        };
    }

    @Override
    public void before() throws Throwable {
        this.jerseyTest.setUp();
    }

    @Override
    public void after() {
        try {
            this.jerseyTest.tearDown();
        } catch (Exception e) {
            throw new RuntimeException("failed to tear down JerseyTest.", e);
        }
    }

    public JerseyTest getJerseyTest() {
        return this.jerseyTest;
    }
}

テスト用の Application クラス

TestResourceConfig.java
package sample.jersey;

import org.glassfish.jersey.server.ResourceConfig;

public class TestResourceConfig extends ResourceConfig {

    public TestResourceConfig() {
        register(SampleResource.class);
    }
}

テストクラス

SampleResourceTest.java
package sample.jersey;

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;

import org.junit.Rule;
import org.junit.Test;

public class SampleResourceTest {

    @Rule
    public JerseyTestRule rule = new JerseyTestRule(new TestResourceConfig());

    @Test
    public void test() {
        String response = rule.getJerseyTest().target("sample").request().get(String.class);
        assertThat(response, is("sample resource"));
    }
}

参考

17
15
0

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
17
15