Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  * Copyright (c) 2007 Mockito contributors
  * This program is made available under the terms of the MIT License.
 package org.mockito.internal.stubbing.defaultanswers;
Optional Answer that can be used with org.mockito.Mockito.mock(java.lang.Class,org.mockito.stubbing.Answer)

This implementation can be helpful when working with legacy code. Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException. This implementation of Answer returns SmartNulls instead of nulls. SmartNull gives nicer exception message than NPE because it points out the line where unstubbed method was called. You just click on the stack trace.

ReturnsSmartNulls first tries to return ordinary return values (see ReturnsMoreEmptyValues) then it tries to return SmartNull. If the return type is not mockable (e.g. final) then ordinary null is returned.

ReturnsSmartNulls will be probably the default return values strategy in Mockito 2.0

public class ReturnsSmartNulls implements Answer<Object> {
    private static final long serialVersionUID = 7618312406617949441L;
    private final class ThrowingInterceptor implements MethodInterceptor {
        private final InvocationOnMock invocation;
        private final Location location = new Location();
        private ThrowingInterceptor(InvocationOnMock invocation) {
            this. = invocation;
        public Object intercept(Object objMethod methodObject[] argsMethodProxy proxythrows Throwable {
            if (new ObjectMethodsGuru().isToString(method)) {
                return "SmartNull returned by unstubbed " + .getMethod().getName() + "() method on mock";
            new Reporter().smartNullPointerException();
            return null;
    private final Answer<Objectdelegate = new ReturnsMoreEmptyValues();
    public Object answer(final InvocationOnMock invocationthrows Throwable {
        Object defaultReturnValue = .answer(invocation);
        if (defaultReturnValue != null) {
            return defaultReturnValue;
        Class<?> type = invocation.getMethod().getReturnType();
        if (..canImposterise(type)) {
            return ..imposterise(new ThrowingInterceptor(invocation), type);
        return null;
New to GrepCode? Check out our FAQ X