I have a method with some logic and an exception block and would like to test the contents in the exception block.
Method:
Class Validator() {
protected Validator(blah,blah) {
}
protected boolean doStuff(String a, String b) {
try {
isValidInput(a){
} catch (Exception e) {
b = "unknown error"
}
}
test case:
@Test
public void testException() {
Validator testValidator = new testValidator(blah, blah);
Validator spy = spy(testValidator);
String var2 = "unknown error"
doReturn(new Exception()).when(spy.doStuff(var1, var2));
assertEquals("unknown error", var2);
}
How can I force the real method to go into exception block and continue stubbing?
Firstly, forget about using
spy– ifisValidInputis able to throw an exception, then make it throw an exception.If there is a collaborator used within
isValidInput()that can throw anException, then mock that using Mockito. If it’s just your code, then you should be able to setasuch that it will generate an exception.You still need to write a full set of tests on
isValidInput()– investigate using theexpectedoption in the @Test annotation (I assume you’re using JUnit here) to specify that throwing an exception is the expected outcome of the test. But please don’t throwException– using a meaningful subclass of it 🙂And as @Dave Newton commented, testing
var2is never going to work outside the scope ofdoStuff.