Skip to content

Instantly share code, notes, and snippets.

@webdevwilson
Created January 12, 2012 18:45
Show Gist options
  • Save webdevwilson/1602314 to your computer and use it in GitHub Desktop.
Save webdevwilson/1602314 to your computer and use it in GitHub Desktop.
Base test class
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.OngoingStubbing;
public abstract class BaseTest<T>
{
private final Class<T> classUnderTest;
protected final T testObject;
protected final MockContainer mocks;
public BaseTest()
{
try
{
mocks = new MockContainer();
MockitoAnnotations.initMocks(mocks);
classUnderTest = getGenericTypeParameter();
final Constructor<T> c = findConstructorWithMostArguments();
final Object[] arguments = buildArgumentListUsingMocks(c.getParameterTypes());
testObject = c.newInstance(arguments);
} catch( final Throwable t)
{
throw new RuntimeException( t );
}
}
private Class getGenericTypeParameter()
{
return (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
private Constructor<T> findConstructorWithMostArguments()
{
final Constructor<T>[] constructors = (Constructor<T>[]) classUnderTest.getConstructors();
Constructor returner = constructors[0];
if (constructors.length > 1)
{
for (final Constructor c : classUnderTest.getConstructors())
{
returner = c.getParameterTypes().length > returner.getParameterTypes().length ? c : returner;
}
}
return returner;
}
private Object[] buildArgumentListUsingMocks(final Class[] argumentTypes) throws Exception
{
final Object[] returner = new Object[argumentTypes.length];
for (Integer i = 0; i < argumentTypes.length; i++)
{
returner[i] = findMockOfType(argumentTypes[i]);
}
return returner;
}
private <T> T findMockOfType(final Class<T> clazz) throws Exception
{
for (final Field f : mocks.getClass().getDeclaredFields())
{
if (f.getType() == clazz)
{
f.setAccessible(true);
return (T) f.get(mocks);
}
}
return null;
}
public <T> void assertThat(T actual, Matcher<T> matcher)
{
assertThat("", actual, matcher);
}
public <T> void assertThat(String message, T actual, Matcher<T> matcher)
{
Assert.assertThat(actual, matcher);
}
public <T> OngoingStubbing<T> when(T methodCall)
{
return Mockito.when(methodCall);
}
public <T> T verify(T mock)
{
return Mockito.verify(mock);
}
public <T> org.hamcrest.Matcher<T> equalTo(T operand)
{
return Matchers.equalTo(operand);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment