Tuesday, 13 December 2011

How to write unit test for private method in java

/**
  * Method: parseDateTime(String text)
 */
 @Test
 public void testParseDateTime() throws Exception {
     try {
        CsvToXml csvToXml = new CsvToXml();
        Method method = CsvToXml.class.getDeclaredMethod("parseDateTime", String.class);
        method.setAccessible(true);
        String actual = (String) method.invoke(csvToXml, "2011-11-08T13:04:31.000+11:00");
        String expect = "2011-11-08T12:04:31Z";
        assertEquals(expect, actual);
     } catch (NoSuchMethodException e) {
        fail(e.getMessage());
     } catch (IllegalAccessException e) {
        fail();
     } catch (InvocationTargetException e) {
        fail();
     }
}

BTW. Another choice is PowerMock Framework

No comments:

Post a Comment