Close

Mockito - Stubbing consecutive method calls

[Last Updated: Aug 11, 2020]

We can stub a method with multiple return values for the consecutive calls.

This can be achieved by passing multiple values to Mockito#thenReturn() method or by calling it multiple times in chain:

Mockito.when(myService.doSomething()).thenReturn(10, 20);
myService.doSomething()// returns 10
myService.doSomething()// returns 20
Mockito.when(myService.doSomething()).thenReturn(10).thenReturn(20);
myService.doSomething()// returns 10
myService.doSomething()// returns 20

Typical use case for this kind of stubbing could be mocking iterators.

Example

Example Application

mockito-consecutive-method-calls-stubbing/src/main/java/com/logicbig/example/MyService.java

package com.logicbig.example;

public interface MyService {
  public int doSomething();
}

mockito-consecutive-method-calls-stubbing/src/main/java/com/logicbig/example/MyProcessor.java

package com.logicbig.example;

public class MyProcessor {
  private MyService myService;

  public MyProcessor(MyService myService) {
      this.myService = myService;
  }

  public String process() {
      int returnInteger = myService.doSomething();
      return String.format("My Integer is: " + returnInteger);
  }
}

Stubbing consecutive method calls

mockito-consecutive-method-calls-stubbing/src/test/java/com/logicbig/example/ProcessorTest.java

package com.logicbig.example;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

public class ProcessorTest {

  @Test
  public void processTest() {
      MyService myService = Mockito.mock(MyService.class);
      Mockito.when(myService.doSomething()).thenReturn(10, 20);
      MyProcessor myProcessor = new MyProcessor(myService);
      String returnedValue = myProcessor.process();
      System.out.println(returnedValue);
      Assert.assertEquals(returnedValue, "My Integer is: 10");
      returnedValue = myProcessor.process();
      System.out.println(returnedValue);
      Assert.assertEquals(returnedValue, "My Integer is: 20");
  }
}
D:\mockito-consecutive-method-calls-stubbing>mvn test -Dtest="ProcessorTest"
[INFO] Scanning for projects...
[INFO]
[INFO] ---< com.logicbig.example:mockito-consecutive-method-calls-stubbing >---
[INFO] Building mockito-consecutive-method-calls-stubbing 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mockito-consecutive-method-calls-stubbing ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\example-projects\mockito\stubbing-methods\mockito-consecutive-method-calls-stubbing\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ mockito-consecutive-method-calls-stubbing ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ mockito-consecutive-method-calls-stubbing ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\example-projects\mockito\stubbing-methods\mockito-consecutive-method-calls-stubbing\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ mockito-consecutive-method-calls-stubbing ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mockito-consecutive-method-calls-stubbing ---
[INFO] Surefire report directory: D:\example-projects\mockito\stubbing-methods\mockito-consecutive-method-calls-stubbing\target\surefire-reports

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.ProcessorTest
My Integer is: 10
My Integer is: 20
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.819 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.914 s
[INFO] Finished at: 2020-04-22T00:02:36-05:00
[INFO] ------------------------------------------------------------------------

Calling thenReturn() in chain:

mockito-consecutive-method-calls-stubbing/src/test/java/com/logicbig/example/ProcessorTest2.java

package com.logicbig.example;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

public class ProcessorTest2 {

  @Test
  public void processTest() {
      MyService myService = Mockito.mock(MyService.class);
      Mockito.when(myService.doSomething()).thenReturn(10).thenReturn(20);
      MyProcessor myProcessor = new MyProcessor(myService);
      String returnedValue = myProcessor.process();
      System.out.println(returnedValue);
      Assert.assertEquals(returnedValue, "My Integer is: 10");
      returnedValue = myProcessor.process();
      System.out.println(returnedValue);
      Assert.assertEquals(returnedValue, "My Integer is: 20");
  }
}
D:\mockito-consecutive-method-calls-stubbing>mvn test -Dtest="ProcessorTest2"
[INFO] Scanning for projects...
[INFO]
[INFO] ---< com.logicbig.example:mockito-consecutive-method-calls-stubbing >---
[INFO] Building mockito-consecutive-method-calls-stubbing 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mockito-consecutive-method-calls-stubbing ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ mockito-consecutive-method-calls-stubbing ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ mockito-consecutive-method-calls-stubbing ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ mockito-consecutive-method-calls-stubbing ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mockito-consecutive-method-calls-stubbing ---

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.ProcessorTest2
My Integer is: 10
My Integer is: 20
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.68 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.671 s
[INFO] Finished at: 2020-04-22T00:05:48-05:00
[INFO] ------------------------------------------------------------------------

Iterator style stubbing

mockito-consecutive-method-calls-stubbing/src/test/java/com/logicbig/example/IteratorStyleTest.java

package com.logicbig.example;

import org.junit.Test;
import org.mockito.Mockito;
import java.util.Iterator;

public class IteratorStyleTest {

  @Test
  public void processTest() {
      Iterator<Integer> iterator = Mockito.mock(Iterator.class);
      Mockito.when(iterator.hasNext()).thenReturn(true, true, true, false);
      Mockito.when(iterator.next()).thenReturn(10, 20, 30);
      while (iterator.hasNext()) {
          System.out.println(iterator.next());
      }

  }
}
D:\mockito-consecutive-method-calls-stubbing>mvn test -Dtest="IteratorStyleTest"
[INFO] Scanning for projects...
[INFO]
[INFO] ---< com.logicbig.example:mockito-consecutive-method-calls-stubbing >---
[INFO] Building mockito-consecutive-method-calls-stubbing 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mockito-consecutive-method-calls-stubbing ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ mockito-consecutive-method-calls-stubbing ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ mockito-consecutive-method-calls-stubbing ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ mockito-consecutive-method-calls-stubbing ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mockito-consecutive-method-calls-stubbing ---

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.IteratorStyleTest
10
20
30
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.669 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.310 s
[INFO] Finished at: 2020-04-22T00:06:53-05:00
[INFO] ------------------------------------------------------------------------

Doing some assertions:

mockito-consecutive-method-calls-stubbing/src/test/java/com/logicbig/example/IteratorStyleTest2.java

package com.logicbig.example;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.Iterator;

public class IteratorStyleTest2 {

  @Test
  public void processTest() {
      Iterator<Integer> iterator = Mockito.mock(Iterator.class);
      Mockito.when(iterator.hasNext()).thenReturn(true, true, true, false);

      Mockito.when(iterator.next()).thenReturn(10, 20, 30);
      for (int i = 0; iterator.hasNext(); i++) {
          int next = iterator.next();
          switch (i) {
              case 0:
                  Assert.assertEquals(next, 10);
                  break;
              case 1:
                  Assert.assertEquals(next, 20);
                  break;
              case 2:
                  Assert.assertEquals(next, 30);
                  break;
          }
      }
  }
}
D:\mockito-consecutive-method-calls-stubbing>mvn test -Dtest="IteratorStyleTest2"
[INFO] Scanning for projects...
[INFO]
[INFO] ---< com.logicbig.example:mockito-consecutive-method-calls-stubbing >---
[INFO] Building mockito-consecutive-method-calls-stubbing 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mockito-consecutive-method-calls-stubbing ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ mockito-consecutive-method-calls-stubbing ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ mockito-consecutive-method-calls-stubbing ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ mockito-consecutive-method-calls-stubbing ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mockito-consecutive-method-calls-stubbing ---

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.IteratorStyleTest2
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.725 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.318 s
[INFO] Finished at: 2020-04-22T00:07:40-05:00
[INFO] ------------------------------------------------------------------------

Example Project

Dependencies and Technologies Used:

  • mockito-core 3.3.3: Mockito mock objects library core API and implementation.
  • junit 4.13: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 8
  • Maven 3.5.4

Mockito - Stubbing Consecutive Method Calls Select All Download
  • mockito-consecutive-method-calls-stubbing
    • src
      • main
        • java
          • com
            • logicbig
              • example
      • test
        • java
          • com
            • logicbig
              • example
                • ProcessorTest.java

    See Also