The simplest use of a stub in unit test comes when the system under test (SUT) requires an object, but the test doesn't cause it to be called, or ignores anything it does. Simplestub handles this very simply.

In the following test, the SUT requires an ObjectOutput instance, but never uses it. SimpleStub creates the appropriate stub easily with a call to createStub.

        public void whenObjectIsInstantiated_OutputObjectIsAvailable() {
            MyClass sut = new MyClass(Stub.createStub(ObjectOutput.class));


This works for both interfaces and abstract classes. If the test were to invoke one of the abstract methods, it would return a suitable default value for the return type.

Sometimes a test will use some of the methods of an abstract class, but not all. Again, this is handled simply by implementing the ones needed for the test, and ignoring the rest.

        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 same invocation can be used to instantiate this test object.

         import com.meterware.simplestub.Stub

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