junitmockitotest-class

How to mock throw new customException?


Hope all are doing good.

I am wanted to mock one of my exception which is inside one private method like below :

 private void verifyScenarios(String empid, String token) {
   if (Validation if true)  // Line 1 :
    throw new CustomException("my message"); //Line 2
   else
    any code.    
 }

Line 1: will be true. Line 2 : This line throwing exception because of that my junit test case is failing, Is there any way to mock line 2 and make it success.

Thanks in advance.


Solution

  • Such things are not possible with Mockito, however I believe that all you need is to assert (pass the test) if exception is thrown, because it is a part of your business logic.

    Try @Test(expected = CustomException.class) instead of @Test if you are using JUnit 4. Test will pass only if code will throw your exception.