Different ways of using thenReturn

This post shows 3 different ways of using thenReturn.

1) First way involves configuring the mock object to return only one return value as shown below
when(class1.method1()).thenReturn(2);

The above code instructs Mockito to return 2, whenever we call class1.method1 (once or more than once, the return value will always be 2)

2) Second way involves configuring the mock object to return different values for each consecutive call, as shown below
when(class1.method1()).thenReturn(2, 3, 4);

So when we call class1.method1 first time, the return value will be 2
when we call class1.method1 second time, the return value will be 3
when we call class1.method1 third time, the return value will be 4

3) We can accomplish the same thing discussed in point 2 by another way as shown below
when(class1.method1()).thenReturn(2).thenReturn(3).thenReturn(4);

Below is the complete code


package package8;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class Class1Test {

    @Mock
    private Class1 class1;
    
    @Test
    public void testMethod1() {
        when(class1.method1()).thenReturn(2);
        assertEquals(2, class1.method1());
        
        when(class1.method1()).thenReturn(2, 3, 4);
        assertEquals(2, class1.method1());
        assertEquals(3, class1.method1());
        assertEquals(4, class1.method1());
        
        when(class1.method1()).thenReturn(2).thenReturn(3).thenReturn(4);
        assertEquals(2, class1.method1());
        assertEquals(3, class1.method1());
        assertEquals(4, class1.method1());
    }
}

Leave a Reply