開發與維運

Java單元測試之 Jersey Restful

添加Jersey測試工具的Maven依賴

<dependency>
   <groupId>org.glassfish.jersey.test-framework.providers</groupId>
   <artifactId>jersey-test-framework-provider-jdk-http</artifactId>
   <version>${jersey.version}</version>
   <scope>test</scope>
</dependency>

簡單的Jersey Restful測試示例

DemoRestful.java

@Path("demo")
public class DemoRestful {
  
    @POST
    @Path("/test")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String test(String str) {
  
        return "This is a jersey restful test method.";
    }
}

DemoRestfulTest.java

public class DemoRestfulTest extends JerseyTest {
 
    @Override
    protected void configureClient(ClientConfig config) {
 
        config.register(FastJsonFeature.class);
    }
 
    @Override
    protected Application configure() {
 
        enable(TestProperties.LOG_TRAFFIC);
        enable(TestProperties.DUMP_ENTITY);
 
        ResourceConfig config = new ResourceConfig();
        config.register(FastJsonFeature.class);
        config.packages("com.faw_qm.cloud.platform.*.restful");
 
        return config;
    }
 
    @Test
    public void test() throws Exception {
 
        JSONObject json = new JSONObject();
   
        json.put("name", "test");
 
        Response response = target("demo").path("test").request().
                accept("application/json;charset=UTF-8").post(Entity.json(json));
 
        Assert.assertEquals(response.getStatus(), 200);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *