Overview

When writing unit tests, it is often necessary to create objects that are passed to the System Under Test (SUT). These objects, sometimes known by the generic term, test doubles, sometimes need behavior, and sometimes not, but are usually required.

It is certainly possible to code these test doubles manually, often with the aid of an IDE. But that tends to clutter up a test class, and any addition of or change to methods in the base class or interface will require changes to the test, even if they are not being used.

A common way around this is to use Mock frameworks, specifying the behavior of only the methods of interest. But that specification can sometimes be difficult to read.

Simplestub takes a different approach. The developer writes only enough of a stub as needed by the test, ignoring any other methods. If a pure stub is wanted, the base interface or abstract class is sufficient. SimpleStub will then instantiate a suitable object, filling in any abstract methods automatically and invisibly.

For example, the java.io.ObjectOutput interface has 17 methods in JDK 1.6, but in a test that only expects to write byte arrays, the following stub could be sufficient:

        public abstract class ObjectOutputStub implements ObjectOutput {

            private List<byte[]> bytes = new ArrayList<byte[]>
            boolean closed;

            byte[][] getWrittenBytes() { return b.toArray(new byte[][b.size()]); }
            boolean isClosed() { return closed; }

            public void write(byte[] b) { bytes.add(b); }
            public void close() { closed = true; }
        }
The test class can be instantiated easily:
        import com.meterware.simplestub.Stub;

        ObjectOutputStub objectOutput = Stub.createStub(ObjectOutputStub.class);

Calls to the defined write method will be captured, and may be retrieved as the test progresses. Any call to one of the other methods will do nothing. Alternately, one can set the strict parameter of the annotation. If it is set, calls to the undefined methods will throw an exception, generated by SimpleStub. This can be useful when working to understand the calls made by legacy code.