user2602584
user2602584

Reputation: 797

How to verify if an exception is caught

How to test if an exception is caught with Mockito?

Example:

try{
     int a = 8/0;
catch(ArithmeticException e){
    Logger.error(e.getMessage());
}

Upvotes: 1

Views: 1397

Answers (1)

GhostCat
GhostCat

Reputation: 140457

I guess your problem is that Logger.error() is actually a call to a static method. And "normal" Mokito doesn't allow you to mock calls to static methods.

Thus, there are two choices:

a) you could turn to PowerMokito ... which enables you to mock such calls; and thereby you can simply specify: "I expect that Logger.error() should be called with this kind of exception object". But be warned: PowerMockito and its brother PowerMock come at certain cost; for many people they create more problems than they solve. So, personally, I absolutely do not recommend this option.

b) you could step back, and change your design to not use static methods, like:

class UnderTest {
   SomeLogger logger ... coming into the class via dependency injection

   void foo() {
      try { ... whatever  
      } catch(WhateverException w) {
        logger.error(w....

So, now you are dealing with a method call; and you can create a mock and pass that.

But of course, that only works if you own the logging code for example. And of course, it might be a lot of work. But in the long run, it will pay off.

Final advise: you might want to watch those videos, explaining in great detail what "writing testable code" is actually about.

Upvotes: 3

Related Questions