8

我的测试类有这个方法

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

超级方法只是对 Spring WS 的调用以进行调用 - 以简化形式

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

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

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

实际调用在基类中,我知道我们不能只模拟那个方法。任何指针?

4

2 回答 2

8

Spring does also provide facilities for mocking web service servers as well as requests from clients. The chapter 6.3 in the Spring WS manual shows how to do mocking.

The Spring WS mocking facility changes the behaviour of the Web Service Template, so you can call that method in the super-class - that method would then call the Spring Mock Service Server.

Here is a sample unit test with the Spring mock service server:

@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();
    }
}

The above example will make the mock service server expect exactly one request with the given payload and (if the payload received matches the expected payload) respond with the given response payload.

However, if you only want to verify that the method in the super-class is really called during the test and if you're not interested in the message exchange following that call, you should use Mockito.

If you'd like to use Mockito, I'd suggest the spy (see also Kamlesh's answer). E.g.

// 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));
于 2013-04-19T08:12:14.653 回答
0

正如@Duncan 所说,如果可以的话,使用依赖注入进行组合将是一种方法,然后模拟该依赖项。

如果你不能,那么你可以使用 mockito spy有选择地模拟被测类的方法。

于 2013-04-18T16:18:19.450 回答