Using mocks in tests

Maybe you know the situation. Having a Foo java class which needs testing. But damn, it needs another class which gets data from the database,
does another complicated thing ™, … . So you create a DummyFooSupport class. Which is only used for tests to create default and defined values.

After trying easymock I think it is a better way to use mocks. Mocks are used to imitate classes. You take an interface and tell it how it should behave and
what it should return. This spares you to create dozens of DummyFoo, DummyBar, … classes.

An example?

package org.easymock.samples;

import junit.framework.TestCase;

public class ExampleTest extends TestCase {

    private ClassUnderTest classUnderTest;
    private Collaborator mock;

    protected void setUp() {
        mock = createMock(Collaborator.class);
        classUnderTest = new ClassUnderTest();
        classUnderTest.addListener(mock);
    }

    public void testRemoveNonExistingDocument() {
        replay(mock);
        classUnderTest.removeDocument("Does not exist");
    }
}

Looks complicated. The important thing to see is that Collaborator is an interface from which an object can be created without implementing a Dummy class.
In this case the mock object does nothing. But you can specify which returns methods are giving and lot more. Just look at the documentation (from where this example is also from).

Tags: , , , , ,

One Response to “Using mocks in tests”

  1. Gabor Says:

    seems to be similar to python unit tests and python doctests in a way.

    especially doctests are very sexy in python

    http://docs.python.org/lib/module-doctest.html
    http://docs.python.org/lib/module-unittest.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: