Skip to content

Instantly share code, notes, and snippets.

@benjchristensen
Created October 13, 2011 17:09
Show Gist options
  • Save benjchristensen/1284824 to your computer and use it in GitHub Desktop.
Save benjchristensen/1284824 to your computer and use it in GitHub Desktop.
JUnit and Mockito with Reflection
/**
* Use reflection to allow performing the same tests on all GETTER methods.
*
* @param cache
* @param m
* @param argArray
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private void testGetMethod(Method m, Object[] argArray) throws IllegalAccessException, InvocationTargetException {
CacheObject cache = new CacheObject(actual);
m.invoke(cache, argArray);
m.invoke(cache, argArray);
m.invoke(cache, argArray);
m.invoke(cache, argArray);
// we retrieved 4 times above, but it should have gone to the actualDAO only once (the first time synchronously)
m.invoke(verify(actual, times(1)), argArray);
waitForWindow();
// after the window passed it should have retrieved asynchronously once during a background check
m.invoke(verify(actual, times(1)), argArray);
m.invoke(cache, argArray);
// calling the method again should NOT cause a call to DAO since it should only now occur asynchronously in the background polling thread
m.invoke(verify(actual, times(0)), argArray);
}
/**
* Test that a GET for a given item only goes to the actualDAO once per time window.
*/
@Test
public void testMethodOneOnCache() throws Exception {
testGetMethod(CacheObject.class.getMethod("method1"), new Object[] {});
}
@Test
public void testMethodTwoOnCache() throws Exception {
testGetMethod(CacheObject.class.getMethod("method2", String.class), new Object[] { "argument" });
}
@benjchristensen
Copy link
Author

Sometimes I want to perform a lot of very similar tests with slight variations on different methods.

The example code above is one example of using reflection to allow the main tests (this against a cache) with various different method calls without copy/pasting/modifying over and over.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment