Suddenly, I realized that I really needed to test some
private methods. So, a quick google for “testing private methods java”
brings up a good article by Bill Venners. He lists all possible options to test private methods:
- Don’t test private methods
- Give the methods package access
- Use a nested test class
- Use reflection
Imagine you have a class
MyClass
and it has a private method, myMethod()
. Sorta like this:public class MyClass { private String myMethod(String s) { return s; } }
Then you could use reflection to invoke the method like this:
MyClass myClass = new MyClass(); Method method = MyClass.class.getDeclaredMethod("myMethod", String.class); method.setAccessible(true); String output = (String) method.invoke(myClass, "some input");
setAccessible(true)
which allows the
private method to be called outside the class. And shazam, I can now
test all my private methods. I was really hoping JUnit 4 would provide
some additional facilities specifically for testing private methods, but
not luck.http://saturnboy.com/2010/11/testing-private-methods-in-java/
No comments:
Post a Comment