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:LinkedList mockedList = mock(LinkedList.class);Using the code Steve and I put together you can simplify this to the following single line.
when(mockedList.get(0)).thenReturn("first");LinkedList mockedList = create(aStub(LinkedList.class).returning("first").from().get(0));
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 staticT create(Object methodCall) {
when(methodCall).thenReturn(StubBuilder.current.returnValue);
return (T) StubBuilder.current.mockInstance;
}
public staticStubBuilder 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;
}
public T from() {
return mockInstance;
}
public StubBuilderreturning(Object returnValue) {
this.returnValue = returnValue;
return this;
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.