Execute Non-Public Methods...

Tim always trys to get me to test Actions and I don't want to. That is what Selenium is for... Anyway, there are some methods in Actions that need testing, like validations and such. Here is a method that Tim wrote a while back that I find indespensible:
public Object invokeNonPublicMethod(Object o, String methodName, Object[] args) 
                                                 throws Exception {
  assertNotNull(o);
  assertNotNull(methodName);
  Method methods[] = o.getClass().getDeclaredMethods();
  for (int i = 0; i < methods.length; ++i) {
   if (methodName.equals(methods[i].getName())) {
    try {
     methods[i].setAccessible(true);
     return methods[i].invoke(o, args);
    } catch (Exception e) {
     throw new Exception(e.getCause());
    }
   }
  }
  fail("Method '" + methodName + "' not found in " + o.getClass());
  return null;
 }  
You execute it like this:
FPSActionMessages messages = (FPSActionMessages) invokeNonPublicMethod(action, "validateSearchCriteria", new Object[]{form});
Sweet and simple.  We use it everywhere...

2 comments:

  1. ...and after I wrote that I found out that Apache Commons has that stuff in FieldUtils and MethodUtils...it was a good exercise tho... :)

    http://commons.apache.org/lang/api-release/index.html

    ReplyDelete
  2. Also if you want another jar file that's just for testing you can use junit addons. http://sourceforge.net/projects/junit-addons/

    It has a PrivateAccessor class that does the same thing.

    ReplyDelete

No corporate specific info, please...