Monthly Archives: May 2014

How to mock web services

In black box testing, sometimes we need to test a system which consumes and produces web services. Here is my experience on how to test such a system.

you need to call a the exposed web service and check how the consumed webs services are called. Exposed web service is already provided by the system, and you need only a client to call it. I used CXF. very straight forward and easy.

But the consumed web services are not there yet. They are not in the scope of tests and mostly not in our control at all.

One approach is to create fix implementation of thos web services, again using a library like CXF and  when the callback functions are called, check that the parametrs are passed correctly and resturn a suitable result for test of other parts at the same time.

This approach works fine only for the simplest cases. If you want to test different scenarios, the fixed mock web service should react differently and you have to put the logic inside it. Sometimes you meay need to have more than one implementation and re-publish the service with the alternative implementations. Not beautiful I admit.

A more beautiful approach is to use mocking frameworks. Here I have selected Mockito.

Here are the steps:

First you have to create a mock object, a normal one based on the service interface. I do it via annotation. like this:

static ServiceInterface serviceMock;

But this should be called from a web service. For any strange reason, it could not be done directly. I had to create a reflecter class to do the job:

public class ServiceProxy implements java.lang.reflect.InvocationHandler {
    private Object obj;

    public static Object newInstance(Object obj) {
        return java.lang.reflect.Proxy.newProxyInstance(
            new ServiceProxy(obj));

    private ServiceProxy(Object obj) {
        this.obj = obj;

    public Object invoke(Object proxy, Method m, Object[] args)
        throws Throwable {
        Object result;
        try {
            result = m.invoke(obj, args);
        } catch (Exception e) {
            throw new RuntimeException("unexpected invocation exception: " +

        return result;

then it is easy, you can define your web service mock and start it.

service = (ServiceInterface)         ServiceProxy.newInstance(serviceMock);
serviceEndpoint = Endpoint.publish(
				"http://localhost:8080/myService", service);

Every thing is ready now. you can run the system and use the mock, just like a normal mock.
As an example of the usage, this code tests if a method is called in web service. Obviously all the mock language of Mockito can be used for more complex tests.


Enjoy your testing !

To present it in a more concrete way I have created a sample usage. It could be found here:

There is also a worldline version. It uses resource locator to find web service.