2018年8月23日 星期四

[Java] test Jersey APIs

如果 APIs 裡面用了大量過濾器、constraint,一般的單元測試很難一併測試,Jersey 提供了測試框架就可以很容易一起測試。 其實就是跑一個伺服器起來去呼叫 API。

// build.gradle
dependencies {
    testCompile (
        'org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-grizzly2:2.27'
    )
}

因為我用 Junit5,所以需要稍微調整一下。

import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class ResourceTest extends JerseyTest {

    @Override
    protected Application configure() {
        enable(TestProperties.DUMP_ENTITY);
        enable(TestProperties.LOG_TRAFFIC);
        return new ResourceConfig(HelloResource.class);
    }

    @Override
    @BeforeEach
    public void setUp() throws Exception {
        // patch junit4
        super.setUp();
    }

    @Override
    @AfterEach
    public void tearDown() throws Exception {
        // patch junit4
        super.tearDown();
    }

    @Test
    void test() {
        Response response = target().path("/hello").request().get(); 
        Assertions.assertEquals(200, response.getStatus());
    }
}

參考資料:

沒有留言:

張貼留言

[Java] Invalid HTTP method: PATCH

最近系統需要使用 Netty4,所以把衝突的 Netty3 拆掉,然後就出現了例外。 pom.xml <dependency> <groupId>com.ning</groupId> <artifactId>as...