Mockito 3 Mock Interface Default Method

With the advancement of Java 8, we can define default methods within the interface now. Mockito lets us mock Interface default methods as well.

package com.example.mokito3.sujan;

public interface AppleService {
    default String saveApple(String apple) {
        String appleString = "i love " + apple + " apple";
        return appleString;
    }
}
package com.example.mokito3.sujan;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.mockito.Mockito.mock;

@ExtendWith(MockitoExtension.class)
public class AppleServiceTest {
    @Mock
    private AppleService appleServiceAnnotation;

    @Test
    void saveAppleWithStaticMockTest() {
        AppleService appleServiceStaticMock = mock(AppleService.class);
        String macintoshStaticMock = appleServiceStaticMock.saveApple("Macintosh");
        System.out.println("macintoshStaticMock = " + macintoshStaticMock + " macintoshStaticMock = " + macintoshStaticMock);
    }

    @Test
    void saveAppleWithAnnotationMockTest() {
        String macintoshAnnotation = appleServiceAnnotation.saveApple("Macintosh");
        System.out.println("macintoshAnnotation = " + macintoshAnnotation + " macintoshAnnotation = " + macintoshAnnotation);
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories { jcenter() }
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
    testCompile 'org.mockito:mockito-junit-jupiter:3.4.4'
}
test {
    useJUnitPlatform()
}

follow us on