lundi 21 septembre 2015

Cannot test a class that return a customException

While experimenting JUnit, I am trying to test a simple private method as follows, this method receives a String and make sure it does not include the word 'Dummy' in it.

private void validateString(String myString) throws CustomException {

    if (myString.toLowerCase().matches(".*dummy.*"))
        throw new CustomException("String has the invalid word!");

}

I am trying to access the private method through reflection but the test fails! It shows following exception:

java.lang.AssertionError:Expected test to throw
(an instance of com.myproject.exception.CustomException and exception 
with message a string containing "String has the invalid word!")

Based on answer of this question, I am catching InvocationTargetException as well.

JUnit

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void shouldThrowExceptionForInvalidString() {

        thrown.expect(CustomException.class);
        thrown.expectMessage("String has the invalid word!");

        try {
            MyClass myCls = new MyClass();
            Method valStr = myCls.getClass().getDeclaredMethod(
                    "validateString", String.class);
            valStr.setAccessible(true);
            valStr.invoke(myCls, "This is theDummyWord find it if you can.");
        } catch (InvocationTargetException | NoSuchMethodException
                | SecurityException | IllegalAccessException
                | IllegalArgumentException n) {
            if (n.getCause().getClass() == CustomException.class) {
                throw new CustomException("String has the invalid word!");
            }
        }

    }





Aucun commentaire:

Enregistrer un commentaire