Unit testing Resteasy,使用Resteasy的服务器端模拟框架制作Http Put或Http Post
我写了一个Rest服务,我想测试它。 我想在不运行服务器的情况下运行JUnit测试。为此,我使用RestEasy的服务器端模拟框架 我的问题是,如何使用这个框架在Http主体中使用封送的Java对象发出Http Put或Http Post请求 下面的代码对于Http Get运行良好,但是如何生成Put或Post,可能有人得到了一些示例代码Unit testing Resteasy,使用Resteasy的服务器端模拟框架制作Http Put或Http Post,unit-testing,http,rest,jax-rs,resteasy,Unit Testing,Http,Rest,Jax Rs,Resteasy,我写了一个Rest服务,我想测试它。 我想在不运行服务器的情况下运行JUnit测试。为此,我使用RestEasy的服务器端模拟框架 我的问题是,如何使用这个框架在Http主体中使用封送的Java对象发出Http Put或Http Post请求 下面的代码对于Http Get运行良好,但是如何生成Put或Post,可能有人得到了一些示例代码 @Test public void testClient() throws Exception { Dispatcher dispatcher =
@Test
public void testClient() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
POJOResourceFactory noDefaults = new POJOResourceFactory(
MyClass.class);
dispatcher.getRegistry().addResourceFactory(noDefaults);
{
MockHttpRequest request = MockHttpRequest.get("/message/test/"
+ requestParam);
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
}
}
回复有点晚,但可能对某人有一些用处。 这就是我通常测试PUT请求的方式。希望能有帮助
@Test
public void testPUT() throws Exception {
POJOResourceFactory noDefaults = new POJOResourceFactory(REST.class);
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addResourceFactory(noDefaults);
String url = "your_url_here";
MockHttpRequest request = MockHttpRequest.put(url);
request.accept(MediaType.APPLICATION_JSON);
request.contentType(MediaType.APPLICATION_JSON_TYPE);
// res being your resource object
request.content(res.toJSONString().getBytes());
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals( HttpStatus.SC_CREATED,response.getStatus());
}
您的断言逻辑是相反的。第一个参数是预期结果,第二个参数是实际值。