Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify that exception was caught with Mockito and PowerMock

Is there any way to verify that exception was caught? I mean that in my method there is a situation when I should catch the exception and in test I want to verify that exception was really caught.

like image 460
Anatoly Avatar asked Jul 09 '13 14:07

Anatoly


People also ask

Can Mockito and PowerMock be used together?

Mockito allows us to create mock objects. Since static method belongs to the class, there is no way in Mockito to mock static methods. However, we can use PowerMock along with Mockito framework to mock static methods.

How do I ignore an exception in Mockito?

If you want to ignore a test method, use @Ignore along with @Test annotation. If you want to ignore all the tests of class, use @Ignore annotation at the class level.

Can I mock private methods using Mockito?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.


1 Answers

I think the answer is no -- perhaps you could pull it off with some intense reflection wrangling, but if so I don't think it would be worth your time.

But I think (without seeing your method), you can probably still get full coverage on your method:

  • If your method takes any action after catching the exception, assert or verify that those actions happened.

  • If no action happens after catching the exception, assert or verify that whatever actions were supposed to happen but were cut off by the exception, didn't happen.

  • Finally, (again, not seeing your method I don't know exactly what you're dealing with) if your method is void, and nothing happens after catching the exception, and the last line of logic is what can throw the exception, then consider making your method return a boolean, have it return false if the exception is caught and true otherwise. Then in your test, make a scenario that should cause the exception to be thrown and caught, and test that the method returns false.

like image 198
James Dunn Avatar answered Sep 21 '22 18:09

James Dunn