【问题标题】:Resteasy, Make a Http-Put or Http-Post with Server-side Mock Framework of RestEasyResteasy,用 RestEasy 的服务器端 Mock 框架做一个 Http-Put 或 Http-Post
【发布时间】:2012-10-19 14:11:24
【问题描述】:

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

我的问题是,如何使用此框架在 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());

    }
}

【问题讨论】:

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


    【解决方案1】:

    回复有点晚,但可能对某人有用。 这就是我通常测试我的 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());
    
    }
    

    【讨论】:

    • 你的断言逻辑颠倒了。第一个参数是预期结果,第二个是实际结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 2011-10-19
    • 2015-08-03
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多