Over a million developers have joined DZone.
Platinum Partner

Shorter Syntax for Creating Stubs with Mockito

· Java Zone

The Java Zone is brought to you in partnership with AppDynamics. Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems.

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

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}