Some 10 years later perhaps the best way to test a private method, or any inaccessible member, is via
@Jailbreak from the Manifold framework.
@Jailbreak Foo foo = new Foo();
// Direct, *type-safe* access to *all* foo's members
foo.privateMethod(x, y, z);
foo.privateField = value;
This way your code remains type-safe and readable. No design compromises, no overexposing methods and fields for the sake of tests.
If you have somewhat of a legacy Java application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection.
Internally we're using helpers to get/set
private static variables as well as invoke
private static methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change
private static final variables through reflection.
Method method = TargetClass.getDeclaredMethod(methodName, argClasses);
return method.invoke(targetObject, argObjects);
And for fields:
Field field = TargetClass.getDeclaredField(fieldName);
TargetClass.getDeclaredMethod(methodName, argClasses) lets you look into
private methods. The same thing applies for
setAccessible(true) is required to play around with privates.
There is always the old-fashioned way:
long startTime = System.nanoTime();
long endTime = System.nanoTime();
long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.
Like Adam Paynter suggested, you can also add an inner class to your code, like this:
The code you have entered between the innermost brackets will be executed everytime the component get resized.
Then you add this listener to your component with
You can get your component by using
e.getComponent(). This way you can call any method of your component from inside the inner class like