【问题标题】:mocking web service模拟网络服务
【发布时间】:2011-09-30 21:11:16
【问题描述】:

我想模拟一个 Web 服务调用来测试我的代码。 以下是我要模拟的代码 sn-p。 我想测试 callWebService() 方法。我想要一种在调用 callRestClientService(criteria) 时创建自己的 HttpResponse 的方法。我尝试使用 JMock 和 EasyMock 但无法获得所需的结果。首先,我相信我将无法模拟或创建自己的 HttpResponse。

即使我无法模拟网关调用,我也已经有一个可以调用的本地服务器,但我必须模拟服务器发回的回复以测试不同的场景。

谁能帮我解决这个问题...... 谢谢!!

public class RestClientServiceResponse
{
    public HttpResponse callRestClientService(final RestClientServiceCriteria criteria) throws IOException
    {
        final HttpUriRequest request = buildHttpUriRequest(criteria);
        return executeRestClientServiceCall(request);
    }

    public HttpResponse executeRestClientServiceCall(final HttpUriRequest request) throws IOException
    {
        final HttpClient client = new DefaultHttpClient();
        final HttpResponse httpResponse = client.execute(request);

        return httpResponse;
    }
}


public class CallWebService
{
    public void callWebService()
    {
        HttpResponse httpResponse = null;
        try
        {
            httpResponse = restClient.callRestClientService(criteria);
        }
        catch (final Exception e)
        {
        System.out.println(e);
        }
    }
}

【问题讨论】:

  • 您说“我尝试使用 JMock 和 EasyMock 但无法获得所需的结果”,您能发布您尝试过的内容吗?给我们一些可以合作的东西。

标签: java easymock jmock


【解决方案1】:

如果我理解正确,请使用嵌入式 JettySimple HTTP 服务器之类的东西。我倾向于使用 Simple,因为它通常具有更好的文档。您可以非常轻松地将其设置为返回任何您想要的测试。根据您需要的复杂程度,您甚至可以在服务器中嵌入一个 mock,让您在 mock 上执行正常的 mocking 操作,这些操作被转换为验证 HTTP 请求和准备 HTTP 响应。

【讨论】:

    【解决方案2】:

    SoapUI 是一个为测试 Web 服务而创建的开源工具,它很好地支持服务模拟。请通过this tutorial 了解如何操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多