I Spy Code - Java

Spy on a method

Question:

Write a java program that uses Mockito to spy on a method.

Answer:

Here is a java example that spys on a method with Mockito:

Source: (Example.java)

import org.mockito.Mockito;
import static org.mockito.Mockito.doReturn;
 
public class Example {
 
   public static void main(String[] args) {
 
      Foo foo = new Foo();
      Foo spy = Mockito.spy(foo);
      doReturn(33333).when(spy).getNumber(3);
 
      System.out.println(spy.getNumber(1));
      System.out.println(spy.getNumber(3));
   }
}
 
class Foo {
 
   public int getNumber(int x) {
      return x;
   }
}
 

Output:

$ java Example
1
33333

Questions answered by this page:

mockito call method on mock
java spy on a method
mockito doreturn example

Related Examples

Spy on a method
Void method throws an exception

2