Mockito 3 Nice Mock

To verify mock object, we need to stub it first, which we will see next, but if we don't stub the mock object and try to verify it, it will not throw any exception but will return null. Its an advancement over the Easy Mock framework.

package com.example.mokito3.sujan;

public class AppleService {
    public String saveApple(String apple) {
        System.out.println("i love " + apple + " apple");
        return apple;
    }
}
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 saveAppleMockTest() {
        AppleService appleServiceStaticMock = mock(AppleService.class);
        String macintoshStaticMock = appleServiceStaticMock.saveApple("Macintosh");
        String macintoshAnnotation = appleServiceAnnotation.saveApple("Macintosh");
        System.out.println("macintoshStaticMock = " + macintoshStaticMock + " 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