我有一个实用程序方法来查找特定字段的对象的getter方法(使用反射):

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
    }
}

我想编写一个涵盖SecurityException场景的单元测试,但是如何使getMethod抛出SecurityException?

Javadoc指出getMethod将抛出SecurityException



我宁愿正常触发异常,而不是求助于模拟框架。

最佳答案

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");

请记住在System.setSecurityManager(null)块中调用finally以恢复原始状态。

09-12 05:58