简体   繁体   中英

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.

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.

Hard to give any advice without any example. But if the exception wouldn't be caught it would went up till it reaches the test and the test would fail, because an exception was thrown. I know that doesn't verify that it was caught in a specific block but just that it was caught at all.

What does that exception do in your program if it is not caught? If it causes the program to crash, you can just run your Act part of the test within a try {} block. If it throws an exception you can catch it and fail the test.

Another option, if the cacught exception causes a method to be called, say printToLog() you can verfiy that the method was indeed called with the correct parameters (using mockito).

You should be able to mock the element that you want to throw the exception, so that it does throw the exception and then check that there were no calls to other methods that would be invoked if no exception had occurred.

Also check the state is as expected when an exception is thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM