jeudi 12 août 2021

How to perform testing on Java Reflective API based code?

I'm trying to write a unit test case for a method that makes use of Java's Reflective API to get things done. Following is a small code snippet based on my original code:

public void executeReflectively () {
    SomeClass object = new SomeClass();
    Class className = object.getClass();
    String methodName = fetchMethodName ();

    try {
        Method method = className.getDeclaredMethod(methodName, null);
        method.setAccessible(true)   
        method.invoke(object, null);
    } catch (SomeException e) {
         // Do something with the exception
    }

}

Now, I'm not sure how to proceed ahead with the Unit testing of the above method. I've prepared tests for the methods defined in SomeClass. As far as I can see, since the above method is simply invoking methods from a class for which tests are already written, therefore it doesn't make sense to test it. But then, since I'm performing unit testing, therefore I'm bound to test this code. So, in that case:

  1. Should I even bother to write a unit test case for executeReflectively() ? Please do state your reasoning(and sources of info.) for your answer.
  2. If I'm writing the test cases, then should I also write tests for checking exceptions (especially, NoSuchMethodException, IllegalAccessException, IllegalArgumentException ) for the above method?




Aucun commentaire:

Enregistrer un commentaire