gpt4 book ai didi

java - 如何为 Spring 的 WebServiceTemplate 创建模拟对象?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:00 25 4
gpt4 key购买 nike

我有一个调用现有网络服务的类。我的类正确处理有效结果以及 Web 服务生成的错误字符串。对 Web 服务的基本调用如下所示(尽管已简化)。

public String callWebService(final String inputXml)
{
String result = null;

try
{
StreamSource input = new StreamSource(new StringReader(inputXml));
StringWriter output = new StringWriter();

_webServiceTemplate.sendSourceAndReceiveToResult(_serviceUri, input, new StreamResult(output));

result = output.toString();
}
catch (SoapFaultClientException ex)
{
result = ex.getFaultStringOrReason();
}

return result;
}

现在我需要创建一些单元测试来测试所有成功和失败条件。它不能调用实际的 web 服务,所以我希望有模拟对象可用于 Spring-WS 的客户端。有谁知道可用于 WebServiceTemplate 或任何相关类的模拟对象?我是否应该尝试编写自己的类并修改我的类以使用 WebServiceOperations 接口(interface)而不是 WebServiceTemplate?

最佳答案

Michael 的回答非常接近,但这是有效的示例。

我已经使用 Mockito 进行单元测试,所以我很熟悉这个库。然而,与我之前使用 Mockito 的经历不同,简单地模拟返回结果并没有帮助。我需要做两件事来测试所有用例:

  1. 修改存储在 StreamResult 中的值。
  2. 抛出 SoapFaultClientException。

首先,我需要意识到我不能使用 Mockito 模拟 WebServiceTemplate,因为它是一个具体的类(如果这是必需的,您需要使用 EasyMock)。幸运的是,对 Web 服务的调用 sendSourceAndReceiveToResult 是 WebServiceOperations 接口(interface)的一部分。这需要更改我的代码以期望 WebServiceOperations 与 WebServiceTemplate。

以下代码支持在 StreamResult 参数中返回结果的第一个用例:

private WebServiceOperations getMockWebServiceOperations(final String resultXml)
{
WebServiceOperations mockObj = Mockito.mock(WebServiceOperations.class);

doAnswer(new Answer()
{
public Object answer(InvocationOnMock invocation)
{
try
{
Object[] args = invocation.getArguments();
StreamResult result = (StreamResult)args[2];
Writer output = result.getWriter();
output.write(resultXml);
}
catch (IOException e)
{
e.printStackTrace();
}

return null;
}
}).when(mockObj).sendSourceAndReceiveToResult(anyString(), any(StreamSource.class), any(StreamResult.class));

return mockObj;
}

第二个用例的支持类似,但需要抛出异常。以下代码创建一个包含 faultString 的 SoapFaultClientException。 faultCode 由我正在测试的处理 Web 服务请求的代码使用:

private WebServiceOperations getMockWebServiceOperations(final String faultString)
{
WebServiceOperations mockObj = Mockito.mock(WebServiceOperations.class);

SoapFault soapFault = Mockito.mock(SoapFault.class);
when(soapFault.getFaultStringOrReason()).thenReturn(faultString);

SoapBody soapBody = Mockito.mock(SoapBody.class);
when(soapBody.getFault()).thenReturn(soapFault);

SoapMessage soapMsg = Mockito.mock(SoapMessage.class);
when(soapMsg.getSoapBody()).thenReturn(soapBody);

doThrow(new SoapFaultClientException(soapMsg)).when(mockObj).sendSourceAndReceiveToResult(anyString(), any(StreamSource.class), any(StreamResult.class));

return mockObj;
}

这两个用例可能需要更多代码,但它们适合我的目的。

关于java - 如何为 Spring 的 WebServiceTemplate 创建模拟对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/794899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com