Search code examples
javaunit-testingmockitopowermockito

How to mock Parse Exception for a private static method?


I have this following method below:

    public class DateValidation() {
        private static boolean isValid(String date) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
            dateFormat.setLenient(false);
            try {           
                dateFormat.parse(inDate.trim());
            }   
            catch (ParseException pe) {
                    pe.printStackTrace();
                    return false;
            }
            return true;
        }
    }

And so far this is my mock test:

public void testIsValidDate_Exception() throws Exception {
    PowerMockito.spy(DateValidation.class);
    PowerMockito.doThrow(new ParseException(null,0)).when(DataValidation.class, "isValidDate", "01/012017");
}

But this is where I am stuck. How do I verify that the test throws ParseException? If the input date is in the wrong format, that should throw the ParseException, right?


Solution

  • Firstly, Your method is not throwing any exception(you are catching it and returning false). Then, how can you test that it throws ParseException. So you have to test if the method returns false, this implies it has thrown parseException.
    If you want to test exception thrown, then you should not catch it in your method.
    Secondly, your test method name is really confusing, it reads testIsValidDate, but you are testing for non valid date throwing exception.
    Just do this

    DateValidation spyDateValidation = PowerMockito.spy(DateValidation.class);        
    boolean result = Whitebox.invokeMethod(spyDateValidation, "isValidDate", "01/012017");
    assertFalse(result);