Expectation API

nextMock generates code allowing you to set expectations on the behavior of a class. See ant.html or maven.html to know how to launch the code generation during your build.

The syntax of the nextMock API is very similar to the jmock syntax.

Here is very simple an example. Imagine that you want to test a Dispatcher class like this :

public class Dispatcher 
{
        public void addListener(Listener listener);
        public void fireMessage(String msg);
}

public interface Listener
{
        public void messageFired(String msg);
}

Here a test class verifying that the listener is correctly called.

import org.jmock.MockObjectTestCase;

public class DispatcherTest extends MockObjectTestCase
{
        public static final String MSG = "The message";
                
        public void testFireMessageWithOneListener()
        {
                ListenerMock listenerMock = new ListenerMock(this);
                listenerMock.expects(once()).messageFired_with(eq(MSG));
                
                Dispatcher dispatcher = new Dispatcher();
                dispatcher.addListener(listenerMock.proxy());
                
                dispatcher.fireMessage(MSG);
        }
}

MockObjectTestCase is a specialised JUnit TestCase defined in JMock that :

  • Allows the automatic validation of the mock object (provided that the mock instance has receive the testcase in his constructor)
  • Provides different shortcut function that simplify the expectations (expl : once(), eq(), etc.)

ListenerMock class is the generated Mock class. You can set different kind of expectation thanks to the expects() function. You can also receive an instance of the Listener class with the proxy() method.

The expects function returns an object allowing you to identify which method must be called. In the exemple : messageFired_with.