Wednesday, August 09, 2006

jMock

This is a really cool open source java testing packages which works very well with JUnit. For a simple example we are going to test a publish/subscribe message system. A Publisher sends objects to zero or more Subscribers. We want to test the Publisher

import org.jmock.*;

class PublisherTest extends MockObjectTestCase {

public void testOneSubscriberReceivesAMessage() {

// set up

Publisher publisher = new Publisher();

Mock mockSubscriber = mock(Subscriber.class);

publisher.add((Subscriber) mockSubscriber.proxy());

// expectations Next we define expectations on the mock Subscriber that specify the methods that we expect to be called upon it during the test run.

final String message = "message";

mockSubscriber.expects(once()).method("receive").with( eq(message) );

publisher.publish(message);

}

}

We expect the receive method to be called with a single argument, the message that will be sent. The eq method is defined in the MockObjectTestCase class and specifies a "constraint1" on the value of the argument passed to the subscriber: we expect the argument to be the equal to the message, but not necessarily the same object. (jMock provides several constraint types1 that can be used to precisely specify expected argument values). We don't need to specify what will be returned from the receive method because it has a void return type.

http://www.jmock.org/

Tony

No comments:

Thumbs Up to GitHub Copilot and JetBrains Resharper

Having used AI tool GitHub Copilot since 08/16/2023, I’ve realized that learning GitHub Copilot is like learning a new framework or library ...