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.
I agree with @Stultuske in the comments above and would rewrite the test to:
@Test
public void shouldThrowExceptionForInvalidString() {
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 (Exception e) {
assert(e instanceOf CustomException);
assert(e.getMessage.equals("String has the invalid word!"));
}
}
Or if you want to use ExpectedException
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldThrowExceptionForInvalidString() {
thrown.expect(CustomException.class);
thrown.expectMessage("String has the invalid word!");
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.");
}