Mockito 3 Answere RETURNS DEFAULTS

Answere#RETURNS_DEFAULTS is the default Answere for all un-stubbed mock. It is also called as Nick Mock. It will return an empty value ie zeros, empty collections, nulls, etc as per return type.

package com.example.mokito3.sujan;

public class AppleService {
    public 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.Answers.RETURNS_DEFAULTS;
import static org.mockito.Mockito.mock;

@ExtendWith(MockitoExtension.class)
public class AppleServiceTest {
    @Mock(answer = RETURNS_DEFAULTS)
    private AppleService appleService;

    @Test
    void saveAppleWithStaticMockTest() {
        AppleService appleService = mock(AppleService.class, RETURNS_DEFAULTS);
        String appleName = appleService.saveApple("Macintosh");
        System.out.println("saveAppleWithStaticMockTest appleName = " + appleName);
    }

    @Test
    void saveAppleWithAnnotationMockTest() {
        String appleName = appleService.saveApple("Macintosh");
        System.out.println("saveAppleWithAnnotationMockTest appleName = " + appleName);
    }
}
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