我正在学习库javax.ws.rs
,所以我编写了一个玩具API。
例如,我已经使用了这个 POST
方法。我已经看到有很多用于测试的库,例如 Jersey 或 Rest Assured,但是,如何对响应代码为 200
且内容为 "hello"
?
@POST
@Path("/getFoo")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Foo getFoo(@BeanParam final Foo foo)
{
return new Foo("hello");
}
最佳答案
对于 Jersey Web 服务测试,有多个测试框架,即:Jersey Test Framework ( https://jersey.java.net/documentation/1.17/test-framework.html ) 和 REST-Assured ( https://code.google.com/p/rest-assured ) - 请参阅此处两者的比较/设置 ( http://www.hascode.com/2011/09/rest-assured-vs-jersey-test-framework-testing-your-restful-web-services/ )。
package com.example.rest;
import static com.jayway.restassured.RestAssured.expect;
import groovyx.net.http.ContentType;
import org.junit.Before;
import org.junit.Test;
import com.jayway.restassured.RestAssured;
public class Products{
@Before
public void setUp(){
RestAssured.basePath = "http://localhost:8080";
}
@Test
public void testGetProducts(){
expect().statusCode(200).contentType(ContentType.JSON).when()
.get("/getProducts/companyid/companyname/12345088723");
}
}
关于java - 单元测试 JAX-RS Controller 的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43121234/