public class UnitTestSupportProxy extends Object implements InvocationHandler
For example, a class that wishes to allow its internal cache to be cleared by unit tests, but to disallow production code the same access, might implement something like this:
public class MyClass {
// singleton pattern with our instance stored in the field INSTANCE ...
/** Return a support instance. Calling clear() will clear
* the caches.
*/
public static UnitTestSupport getUnitTestSupport() {
return UnitTestSupportProxy.injectProxy(new MyUTS());
}
// this is our support implementation that clears our caches
private static class MyUTS extends UnitTestSupportAdapter {
// the proxy wrapper will ONLY allow this method to
// run if it determines that the caller is a unit test
// method annotated with a "Before/BeforeClass/After/AfterClass"
@Override
public void clear() {
clearCache();
}
// clear the cache on our singleton instance
private void clearCache() {
synchronized (MyClass.INSTANCE.cache) {
MyClass.INSTANCE.cache.clear();
}
}
}
}
When a method on the UnitTestSupport interface is invoked, the proxy
examines the calling stack to verify that the caller is a method that has
been annotated with any of the following JUnit annotations:
org.junit.BeforeClass org.junit.AfterClass org.junit.Before org.junit.After RuntimeException is thrown.| Modifier and Type | Method and Description |
|---|---|
static UnitTestSupport |
injectProxy(UnitTestSupport obj)
This method returns a proxy wrapper for the given UnitTestSupport
implementation.
|
Object |
invoke(Object proxy,
Method method,
Object[] args) |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
invoke in interface InvocationHandlerThrowablepublic static UnitTestSupport injectProxy(UnitTestSupport obj)
obj - the UnitTestSupport implementationCopyright © 2014. All Rights Reserved.