Stubbing a default interface method

In this post under Mockito, I will explain how to change a default interface method implementation for testing purposes with an example.

For testing purposes I have created an interface as shown below

Interface1


package package6;

public interface Interface1 {
    public default int method1(int value) {
        return value * 2;
    }
}

The test case is as shown below


1  package package6;
2  
3  import static org.junit.Assert.assertEquals;
4  import static org.mockito.ArgumentMatchers.anyInt;
5  import static org.mockito.Mockito.when;
6  
7  import org.junit.Test;
8  import org.mockito.Mockito;
9  
10 public class Interface1Test {
11  @Test
12  public void testMethod1() {
13      Interface1 interface1 = Mockito.mock(Interface1.class);
14      when(interface1.method1(anyInt())).thenReturn(4);
15      
16      assertEquals(4, interface1.method1(1));
17      assertEquals(4, interface1.method1(3));
18  }
19 }

In the above code, at line 13, I create a mock of Interface1.

At line 14, I changed the default interface method implementation to always return 4 regardless of the input.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s