Simplestub is a tool which simplifies the creation of test stubs for unit testing. It does so by filling in any unimlemented method at compile time. 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:
        ObjectOutputStub objectOutput = Stub.create(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 thrown an exception, generated by SimpleStub.


Unit tests often involve stubbing out classes invoked by the System under Test (SUT). The common way to do that is simply to implement all of the abstract methods of an interface or abstract class. That can get cumbersome when there are a lot of them, especially if the test only needs a handful. IDEs can generate empty methods easily; however, that clutters up the test code - and any change to the interface requires updating all of the tests which have stubbed it out, even if the don't use those methods.

One approach to avoid this is to use one of the many Mock libraries, and simply define the behavior for the methods to be used; however, that is not strictly their purpose, and the setup code can be difficult to read and may need to be repeated with small variations from test to test.

SimpleStub takes a middle course. Developers define the behavior they want, and let the tool fill in the rest at compile time. The stub may then be used as usual.