Resteasy,使用RestEasy的服务器端模拟框架制作Http-Put或Http-Post

时间:2012-10-19 14:11:25

标签: unit-testing http rest jax-rs resteasy

我写了一个Rest-Service,我想测试一下。 我想在没有运行服务器的情况下运行JUnit测试。为此,我使用RestEasy的服务器端模拟框架。

我的问题是,如何在Http-Body中使用带有编组的Java对象的框架发出Http-Put或Http-Post请求?

以下代码适用于Http-Get,但是如何制作Put或Post,也许有人为此获得了一些示例代码???

@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());

    }
}

1 个答案:

答案 0 :(得分:6)

有点迟到的反应,但可能对某人有用。 这就是我通常测试我的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());

}