Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to Test Catch Block?

Bit of a repost, but a certain catch-22 about not having enough reputation means I can't comment on any of the duplicate threads! (cough cough)

I'm trying to test the catch block of a try-catch using Mockito; is it possible to make a mock throw an exception that is handled by the method being tested? I can't use doThrow()...when()... or @Test(expected = Foo.class) because the exception is handled. I want to test that the method handles Exceptions properly.

@Controller
public class StockExchangeController {

    public ModelAndView placeOrder(ModelAndView mav, MyObj myObj) {

        try {
            validator.validate(myObj); // Throws CustomException if validation fails
            mav.setViewName("successPage");

        } catch (CustomException ex) {
            mav.setViewName("failPage");
        }

        return mav;
    }
}

I'd like to be able to stub the behaviour of my "validatorObject", like

doThrow(new CustomException()).when(validatorMock).validate();

Is there a way to do this?

The answer here (Test catch block logic with Junit and mockito) doesn't work (I believe) because the exception is handled before it gets to test level.

Tips and thoughts much appreciated!

like image 360
Danny Salvadori Avatar asked Aug 06 '26 22:08

Danny Salvadori


1 Answers

BDD Style Solution

Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception

Mockito + Catch-Exception + AssertJ
given(otherServiceMock.bar()).willThrow(new MyException());

when(myService).foo();

then(caughtException()).isInstanceOf(MyException.class);
Sample code
  • Mockito + Catch-Exception + Assertj full sample
Dependencies
  • eu.codearte.catch-exception:catch-exception:1.3.3
  • org.assertj:assertj-core:1.7.0
Disadvantage
  • Only Mockito up to 1.10.8 is supported
like image 94
Hemant Singh Avatar answered Aug 09 '26 12:08

Hemant Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!