Here is a snippet of a unit test that someone had written.
public class SomeTest {
private Method logMethod;
@BeforeMethod
public void setup() throws NoSuchMethodException {
logMethod = TheServlet.class.getDeclaredMethod(
"logEvent", new Class[] {
Parameter1.class,
Parameter2.class,
Parameter3.class}
);
}
@Test
public void testLogging() throws Exception {
logMethod.setAccessible(true);
// some set-up
logMethod.invoke(null, parameter1, parameter2, parameter3);
// asserts
}
}
Holy! I have seldom seen crappier code (and I am not even going to talk about having to catch Exception in the test method). Someone was getting a reference to the previously private static method inside the Servlet class, to be able to make it accessible via Reflection and invoke it from the test. Really, a design smell could not be more apparent. If you want to test the method, in that case it was doing some logging to the database, write a collaborator class to do the logging for you, that can be tested in isolation and is injected as a dependency. It is always good to take a step backwards and look at the million things you have to do in order to test stuff. This will most likely guide you to a better design of your software.
0 Kommentare:
Kommentar veröffentlichen