java - Mockito pattern for a Spring web service call -
my class under test has method
public somewebserviceresponse calldownstream(somewebservicerequest request) { return (somewebserviceresponse ) super.callservice(request); }
the super method call spring ws make call - in simplified form
response = getwebservicetemplate().marshalsendandreceive(this.getbaseurl(), request); return response;
when write unit test tried make actual web service call. i'm not clear how mock or rather should mocking.
should loading sample response filesystem , looking string in - in case i'm testing file loading.
the actual call in base class , know can't mock method. pointers?
spring provide facilities mocking web service servers requests clients. chapter 6.3 in spring ws manual shows how mocking.
the spring ws mocking facility changes behaviour of web service template, can call method in super-class - method call spring mock service server.
here sample unit test 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 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 make mock service server expect 1 request given payload , (if payload received matches expected payload) respond given response payload.
however, if want verify method in super-class called during test , if you're not interested in message exchange following call, should use mockito.
if you'd use mockito, i'd suggest spy (see kamlesh's answer). e.g.
// decorates spy. myclass myspy = spy(this); // change behaviour of callwebservice method return specific response doreturn(mockresponse).when(myspy).callwebservice(any(somewebservicerequest.class)); // invoke method tested. instance.calldownstream(request); // verify callwebservice has been called verify(myspy, times(1)).callwebservice(any(somewebservicerequest.class));
Comments
Post a Comment