From [Joe's Jelly]
Quick Tip: Keeping unit tests in parallel source trees
It's common practise to bundle unit-tests in the same source tree as production code. To distinguish between test code and production code, tests are placed in a subpackage called test.
<snip>
However, if tests are kept in parallel source trees and the test subpackage is ditched, it gives some useful advantages:
<snip>
[Joe's Jelly]
My opinion is keep them in sub-packages in the same tree. Even if you have your test classes in the same package, you still can't access private methods / fields, which are sometimes worth testing (especially if you have an algorithm in a private method). Besides which, having 2 source trees is a pain in the nuts (I can't think immediately of a quick way of doing it nicely in IDEA), and it really isn't too hard to tell Ant to not bother with test classes for production builds or JavaDocs (sorry Joe! :) )
To get around this, I've been using reflection to get at private members (which works if your Security Manager lets you, which it does by default), which is totally legitimate at test-time (even though at production run-time you'd probably want to do something more reasonable).
You can have a class which has a set of utility methods to let you do such things and, for example, you could use the following to get at normally inacessable methods (credit to Mike Royle, fellow ThoughtWorker, for this): public static Object callInacessableMethod(Object targetObject, String methodName, Class[] parameterTypes, Object[] parameterValues) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Method method = getMethodByName(targetObject.getClass(), methodName, parameterTypes); method.setAccessible(true); return method.invoke(targetObject, parameterValues); } private static Method getMethodByName(Class target, String name, Class[] parameterTypes) throws NoSuchMethodException{ try { return target.getDeclaredMethod(name, parameterTypes); } catch (NoSuchMethodException e) { if (target.equals(Object.class)) throw e; return getMethodByName(target.getSuperclass(), name, parameterTypes); } }
In the meantime, I'm going to go and figure out how to quote other people nicely in my blog...
9:35:26 PM
|