Jay Fields is a software developer at DRW Trading. He has a passion for discovering and maturing innovative solutions. His most recent work has been in the Domain Specific Language space where he's delivered applications that empowered subject matter experts to write the business rules of the applications. He is also very interested in maturing software design through software testing. Jay is a DZone MVB and is not an employee of DZone and has posted 116 posts at DZone. You can read more from them at their website. View Full User Profile

Shorter Syntax for Creating Stubs with Mockito

02.27.2010
| 5364 views |
  • submit to reddit

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:

LinkedList mockedList = mock(LinkedList.class);
when(mockedList.get(0)).thenReturn("first");
Using the code Steve and I put together you can simplify this to the following single line.
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 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;
}

public T from() {
return mockInstance;
}

public StubBuilder returning(Object returnValue) {
this.returnValue = returnValue;
return this;
}
}
}

From http://blog.jayfields.com

Published at DZone with permission of Jay Fields, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Michael Vitz replied on Sun, 2010/02/28 - 7:06am

Hi.

I like this syntax, but I can't get this working. The compiler complains about the missing reference for the Typeparameter T. Are you sure this is the exact code you are using?

Steven Baker replied on Mon, 2010/08/30 - 1:35am

Sample code does not work. :-(

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.