Mockito 3 Answere RETURNS SMART NULLS

Mockito works on mocks and stubs, desired methods are stubbed for inputs and will return predefined output. If a request is not stubbed Mockito framework has a feature called nice mock which will return null whereas Easy Mock framework will throw an exception.

The response returned from Easy mock will still throw NullPointerException if any functionality is called on null. To avoid this Mockito provides us the RETURNS_SMART_NULLS feature, it will return SmartNull with a nice clear exception rather than NullPointerException.

SmartNull will point out the line in stack trace where the unstubbed method was called and result in NullPointerException.

RETURNS_SMART_NULLS probably will be the default return values strategy in Mockito 4

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_SMART_NULLS;
import static org.mockito.Mockito.mock;

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

    @Test
    void saveAppleWithStaticMockTest() {
        AppleService appleService = mock(AppleService.class, RETURNS_SMART_NULLS);
        String appleName = appleService.saveApple("Macintosh");
        System.out.println("saveAppleWithStaticMockTest appleName = " + appleName);
        /* will not throw null pointer exception */
        System.out.println("saveAppleWithStaticMockTest appleName = " + appleName.toUpperCase());
    }

    @Test
    void saveAppleWithAnnotationMockTest() {
        String appleName = appleService.saveApple("Macintosh");
        System.out.println("saveAppleWithAnnotationMockTest appleName = " + appleName);
        /* will not throw null pointer exception */
        System.out.println("saveAppleWithAnnotationMockTest appleName = " + appleName.toUpperCase());
    }
}
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