Reputation: 9928
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.
Upvotes: 8
Views: 3397
Reputation: 1565
As far as causing this in a regular setting, there are very little cases where this can happen.
Non-public methods will result in a NoSuchMethodException
, because getMethod
specifically looks for public methods only. getDeclaredMethod
will find the method, but allows private/protected methods to be returned.
The only real way to do this is to, as the javadocs say, have a separate package that is protected by the security manager, which I'm guessing can only be done with unsigned applets or similar permissions. (I have never run into this myself, so I am not entirely sure)
Your best bet is forcing the exception to be thrown for specific methods by overriding the security manager.
Upvotes: 0
Reputation: 597362
System.setSecurityManager(new SecurityManager(){
@Override
public void checkMemberAccess(Class<?> clazz, int which) {
throw new SecurityException("Not allowed")
}
@Override
public void checkPermission(Permission perm) {
// allow resetting the SM
}
});
ClassTest.class.getMethod("foo");
Remember to call System.setSecurityManager(null)
in a finally
block to restore the original state.
Upvotes: 11