<< User Mental Models | Home | DCI Plugin for Eclipse >>

Dynamic Mock Testing

Have you ever had to create a mock object in which most methods do nothing and are not called, but in others something useful needs to be done?

EasyMock has some newish functionality to let you stub individual methods. But before I had heard about that, I had built a little framework (one base class) for creating mock objects which stubs those methods you want to stub, as well as logging every call made to the classes being mocked.

It works like this: you choose a class which you need to mock, for example a service class called FooService, and you create a new class called FooServiceMock. You make it extend from AbstractMock<T>, where T is the class you are mocking.

As an example:

public class FooServiceMock extends AbstractMock<FooService> {

    public FooServiceMock() {

It needs to have a constructor to call the super constructor passing the class being mocked too. Perhaps that could be optimised, I don't have too much time right now.

Next, you implement only those methods you expect to be called. For example:

public class FooServiceMock extends AbstractMock<FooService> {

    public FooServiceMock() {

     * this is a method which exists in FooService, 
     * but I want it to do something else.
    public String sayHello(String name){
	    return "Hello " + name + 
              ", Foo here!  This is a stub method!";

To use the mock, you'll notice that it doesn't extend the class which it mocks, which might be problematic... Well, there are good reasons. To do the mocking, the abstract base class is actually going to create a dynamic proxy which wraps itself behind the interface of the class being mocked. To the caller, it looks like the FooService, but it's not actually anything related to it. Anytime a call to the FooService is made, the first thing which the proxy does is log that call, using XStream to create an XML representation of the parameters being passed into the method. Then, the proxy goes and looks in the instance of the mock class to see if it can find the method being called (well at least a method which takes the same parameters and has the same name and return type). If it finds such a method, it calls it. In our example, the sayHello(String) method would get called. It returns the result if there is one, to the caller.

In the case where it cannot find the method, it throws an exception, because it assumes that if it was not implemented, you didn't expect it to be called. You could of course change this to suit your needs, maybe even calling the actual FooService.

So, how to you use the FooServiceMock to create a FooService instance which you can use to mock your service? In the test, where you setup the class under test, you do this:

    FooServiceMock fooService = new FooServiceMock();
    //perhaps tell it about objects you would
    //like it to return...

The setFooService(FooService) method on the instance of the class you are testing is in my case present, but you might not have it and may need to use reflection to do it. It's a question of how testable you write your classes, and is a design choice.

The getMock() method on the AbstractMock class is the method which creates the dynamic proxy which wraps the instance of the mock.

You can now test the class. There is however still something useful you can do after testing, i.e. assert that the right calls were made in the correct order with the right parameters. You do this in the test class to:

    assertEquals(1, fooService.getCalls().size());
    assertEquals("[sayHello: <String>Ant</String>]", 

The above tests that the sayHello(String) method was called just once, and passed the name "Ant".

There are times when you might want to clear the call log, between parts of the test. For that, call the clearCalls() method on the mock object:


Finally, here is the code for the AbstractMock, which you might want to tweak, depending upon your needs:

 * Copyright (c) 2010 Ant Kutschera, maxant
 * This file is part of Ant Kutschera's blog, 
 * http://blog.maxant.co.uk
 * This is free software: you can redistribute
 * it and/or modify it under the terms of the
 * Lesser GNU General Public License as published by
 * the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * It is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied
 * PURPOSE.  See the Lesser GNU General Public License for
 * more details. You should have received a copy of the
 * Lesser GNU General Public License along with the blog.
 * If not, see .
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;

 * base class for mocks who need to log their calls.
 * @author   Ant Kutschera
public abstract class AbstractMock {

* xstream is used for creating a serialised xml
* representation of objects
private XStream xstream = new XStream();

/** every call to the class being mocked is logged */
private List calls = new ArrayList();

* the interface which needs to be exposed, ie the
* class of the object being mocked
private Class interfaceClass;

* Creates a new AbstractMock object.
* @param interfaceClass the class of the object
* being mocked
public AbstractMock(Class interfaceClass){
this.interfaceClass = interfaceClass;

* @return a list of strings, one for each call
* containing the method name followed by each
* parameter as an XML string as created by XStream.
public List getCalls() {
return calls;

* resets the list of calls.
public void clearCalls() {

* @return a proxy which wraps the instance, so
* that it can automatically handle
* unimplemented methods.
@SuppressWarnings({ "unchecked", "rawtypes" })
public T getMock() {
ClassLoader classLoader = getClass().getClassLoader();
Class[] interfaces = new Class[] { interfaceClass };
InvocationHandler ih = new InvocationHandler() {

public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {

Method m = getMethod(method);

if (m == null) {
//TODO you could change this if you like...
//maybe make it configurable?
throw new RuntimeException("unexpected call to "+
"a method not in the mock: " + method);
} else {
String s = m.getName();
if (args != null) {
for (Object o : args) {
s += ":" + xstream.toXML(o);

//trim white space between xml tags as well as
//new lines anywhere!
s = s.replaceAll("\r", "").replace("\n", "");
for (int i = 0; i < 10; i++) {
char[] spaces = new char[i * 2];
for (int j = 0; j < spaces.length; j++) {
spaces[j] = ' ';
s = s.replaceAll(">" + new String(spaces) +
"<", "><");

//log the call...

//now call the mock implementation!
return m.invoke(AbstractMock.this, args);

return (T) Proxy.newProxyInstance(classLoader,
interfaces, ih);

* the method with the same name/params, if it exists in
* this class, otherwise null.
private Method getMethod(Method method) throws
IllegalAccessException, InvocationTargetException {

for (Method domainObjectMethod :
getClass().getMethods()) {

if (match(method, domainObjectMethod)) {
return domainObjectMethod;

return null;

private static boolean match(Method method1,
Method method2) {
return namesAreEqual(method1, method2)
&& typesAreEqual(method1, method2);

private static boolean namesAreEqual(Method method1,
Method method2) {
return method2.getName().equals(method1.getName());

private static boolean typesAreEqual(Method method1,
Method method2) {
Class[] types1 = method1.getParameterTypes();
Class[] types2 = method2.getParameterTypes();

if (types1.length != types2.length) {
return false;

for (int i = 0; i < types1.length; ++i) {
if (!types1[i].equals(types2[i])) {
return false;
return true;

Have fun!
©2010 Ant Kutschera

Tags : , ,
Social Bookmarks :  Add this post to Slashdot    Add this post to Digg    Add this post to Reddit    Add this post to Delicious    Add this post to Stumble it    Add this post to Google    Add this post to Technorati    Add this post to Bloglines    Add this post to Facebook    Add this post to Furl    Add this post to Windows Live    Add this post to Yahoo!

Re: Dynamic Mock Testing

Nice one line solution. And they say Java is verbose.

Re: Dynamic Mock Testing

Is there a reason why you use XStream for serialization? Can java.beans.XMLEncoder/XMLDecoder be used instead?

Re: Dynamic Mock Testing

XMLEncoder or simply calling the toString method (as long as its implemented) on parameters would work just as well. You could also modify the AbstractMock and pass it an instance of the real class you are mocking in the constructor, and then, if the method isn't found in the mock, the proxy could call the real class. The possibilities are endless really! See JMock and EasyMock too though, they might be even more suited to your needs.

Add a comment Send a TrackBack