java - 用于 Spring Web 服务调用的 Mockito 模式

标签 java junit mockito spring-ws

我的被测类有这个方法

public SomeWebServiceResponse callDownstream(SomeWebServiceRequest request)  {
    return (SomeWebServiceResponse ) super.callService(request);
}

super 方法只是调用 Spring WS 来进行调用 - 简化形式

response = getWebServiceTemplate().marshalSendAndReceive(this.getBaseURL(), 
    request);
return response;

当我编写单元测试时,它试图进行实际的 Web 服务调用。我不清楚如何 mock 这个或者我们应该 mock 什么。

我是否应该从文件系统加载示例响应并在其中寻找一些字符串 - 在这种情况下我只测试文件加载。

实际调用在基类中,我知道我们不能只模拟那个方法。有什么指点吗?

最佳答案

Spring 还提供了模拟 Web 服务服务器以及来自客户端的请求的工具。 Spring WS manual中的第6.3章展示了如何进行模拟。

Spring WS 模拟工具更改了 Web 服务模板的行为,因此您可以在父类(super class)中调用该方法 - 然后该方法将调用 Spring 模拟服务服务器。

这是一个使用 Spring 模拟服务服务器的示例单元测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-ws.xml"})
public class SetStatusFromSrsTemplateTest {
    @Autowired
    private WebServiceTemplate wsTemplate;

    @Before
    public void setUp() throws Exception {
        mockServer = MockWebServiceServer.createServer(wsTemplate);
    }

    @Test
    public void testCall() {
        SomeWebServiceRequest sampleRequest = new SomeWebServiceRequest();
        // add properties to the sampleRequest...
        Source expectedPayload = new ResourceSource(new ClassPathResource("exampleRequest.xml"));
        Source expectedResponse = new ResourceSource(new ClassPathResource("exampleResponse.xml"));
        mockServer.expect(payload(expectedPayload)).andRespond(withPayload(expectedResponse));
        instance.callDownStream(sampleRequest);
        mockServer.verify();
    }
}

上面的示例将使模拟服务服务器准确地期望一个具有给定有效载荷的请求,并且(如果收到的有效载荷与预期的有效载荷匹配)使用给定的响应有效载荷进行响应。

但是,如果您只想验证父类(super class)中的方法在测试期间是否真的被调用,并且您对该调用之后的消息交换不感兴趣,那么您应该使用 Mockito。

如果您想使用 Mockito,我建议您使用 spy (另请参阅 Kamlesh 的回答)。例如

// Decorates this with the spy.
MyClass mySpy = spy(this);
// Change behaviour of callWebservice method to return specific response
doReturn(mockResponse).when(mySpy).callWebservice(any(SomeWebServiceRequest.class));
// invoke the method to be tested.
instance.callDownstream(request);
// verify that callWebService has been called
verify(mySpy, times(1)).callWebService(any(SomeWebServiceRequest.class));

关于java - 用于 Spring Web 服务调用的 Mockito 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16081598/

相关文章:

java - 为什么 ModelAtribute 作为 null 传递?

java - 检查 Hamcrest 中的 List 是否为空

java - 类加载器问题 : Exception not caught even if explicitly caught in test

junit - 如何忽略 JUnit 测试方法本身中的测试

java - 如何在不初始化类的情况下模拟内部成员

java - Mockito 可以验证参数是否具有某些属性/字段?

java - 如何在 android 4.4 及更高版本中以编程方式检查我是否打开了 gps?

java - 导入外部 jar 文件

java - PostgreSQL 错误 : canceling statement due to user request

java - 是否可以从 JSP 向 Spring Controller 发送不止一种类型的对象?