Spring Web服务调用的Mockito模式

shi*_*ike 8 java junit spring-ws mockito

我的班级有这种方法

public SomeWebServiceResponse callDownstream(SomeWebServiceRequest request)  {
    return (SomeWebServiceResponse ) super.callService(request);
}
Run Code Online (Sandbox Code Playgroud)

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

response = getWebServiceTemplate().marshalSendAndReceive(this.getBaseURL(), 
    request);
return response;
Run Code Online (Sandbox Code Playgroud)

当我编写单元测试时,它试图进行实际的Web服务调用.我不清楚如何嘲笑这个或者更确切地说我们应该嘲笑什么.

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

实际调用是在基类中,我知道我们不能只模拟该方法.有什么指针吗?

Oli*_*idt 8

Spring还提供了用于模拟Web服务服务器以及来自客户端的请求的工具.Spring WS手册中的第6.3章介绍了如何进行模拟.

Spring WS模拟工具改变了Web服务模板的行为,因此您可以在超类中调用该方法 - 该方法将调用Spring Mock Service Server.

以下是使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的示例将使模拟服务服务器完全期望具有给定有效载荷的一个请求和(如果接收的有效载荷与预期的有效载荷匹配)响应给定的响应有效载荷.

但是,如果您只想验证在测试期间是否真正调用了超类中的方法,并且如果您对该调用后的消息交换不感兴趣,则应使用Mockito.

如果您想使用Mockito,我会建议间谍(另见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));
Run Code Online (Sandbox Code Playgroud)