I Spy Code - Java

Void method throws an exception

Question:

Write a java program that uses Mockito on a method that returns a void and throws an exception.

Answer:

Here is a java example that uses Mockito to test a method that throws an exception.

Source: (Example.java)

import org.mockito.Mockito;
import static org.mockito.Mockito.doThrow;
 
public class Example {
 
   public static void main(String[] args) {
 
      Foo foo = new Foo();
      Foo spy = Mockito.spy(foo);
      doThrow(new IllegalArgumentException("MOCK EXCEPTION")).when(spy).getNumber(55);
 
      try {
         spy.getNumber(0);
         spy.getNumber(1);
         spy.getNumber(55);
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}
 
class Foo {
 
   public void getNumber(int x) {
      if (x < 0) {
         throw new IllegalArgumentException("x is negative.");
      } else {
         System.out.println(x + " is good");
      }
   }
}
 

Output:

$ java Example
0 is good
1 is good
MOCK EXCEPTION

Questions answered by this page:

Mockito test a void method throws an exception
Mocking Exception Throwing using Mockito
Spy on method that trows an exception

Related Examples

Spy on a method
Void method throws an exception

2