I have a utility method to find an object’s getter method for a particular field (using reflection):
public static Method findGetter(final Object object, final String fieldName) {
if( object == null ) {
throw new NullPointerException("object should not be null");
} else if( fieldName == null ) {
throw new NullPointerException("fieldName should not be null");
}
String getterName = getMethodNameForField(GET_PREFIX, fieldName);
Class<?> clazz = object.getClass();
try {
return clazz.getMethod(getterName);
} catch(final NoSuchMethodException e) {
// exception handling omitted
} catch(final SecurityException e) {
// exception handling omitted
}
}
I would like to write a unit test that covers the SecurityException scenario, but how can I make getMethod throw a SecurityException?
The javadoc states that getMethod will throw SecurityException
If a security manager, s, is present and any of the following
conditions is met:
invocation of s.checkMemberAccess(this, Member.PUBLIC) denies access to the method
the caller’s class loader is not the same as or an ancestor of the class loader for the current class and invocation of
s.checkPackageAccess() denies access to the package of this class
I would prefer to trigger the exception normally, rather than resorting to a mocking framework.
Remember to call
System.setSecurityManager(null)in afinallyblock to restore the original state.