This post originated from an RSS feed registered with Ruby Buzz
by Jay Fields.
Original Post: Shorter Syntax for Creating Stubs with Mockito
Feed Title: Jay Fields Thoughts
Feed URL: http://feeds.feedburner.com/jayfields/mjKQ
Feed Description: Blog about Ruby, Agile, Testing and other topics related to software development.
As part of my efforts to create more concise Unit Tests in Java, Steve McLarnon and I recently added the ability to create a stub and stub one method with only one line.
The implementation relies entirely on Mockito, so my example assumes you were already using Mockito to create the stub.
The Mockito documentation has the following example for stubbing:
The implementation is simple, but does rely on static state. There are ways to improve the implementation; however, this works for us. If you have more specific needs, feel free to change it to suit you.
The implementation follows:
public class MockitoExtensions { public static T create(Object methodCall) { when(methodCall).thenReturn(StubBuilder.current.returnValue); return (T) StubBuilder.current.mockInstance; }
public static StubBuilder aStub(Class klass) { return new StubBuilder(mock(klass)); }
public static class StubBuilder { public static StubBuilder current; public final T mockInstance; private Object returnValue;
public StubBuilder(T mockInstance) { current = this; this.mockInstance = mockInstance; }