Published: Wednesday, 27 December 2006

Sample JMock Usage

Find the interface you would like to test. e.g.

public interface ISample {
   public String encode(String s);

Create a Mock for test values. I’ve setup the Mock to encode “1” as a “A”, and “2” as “B”.

// the test case should extend MockObjectTestCase instead of TestCase
... extends MockObjectTestCase

// Usually this is done in the setup method of the junit test.
// here you give it the interface class
Mock sampleMock = new Mock(ISample.class);
// add test values to the mock object
// return a proxy that can be used as a concrete implementation.
ISample impl = (ISample) sampleMock.proxy();