Mohammad Wasim Khan
Mohammad Wasim Khan

Reputation: 115

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.

Upvotes: 0

Views: 1179

Answers (2)

staszko032
staszko032

Reputation: 862

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.

Upvotes: 0

Chris311
Chris311

Reputation: 3992

You can use an expected exception rule. With this solution you can easily check the error message that is thrown as well.

Upvotes: 0

Related Questions