All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.mockito.internal.stubbing.defaultanswers.ReturnsMocks Maven / Gradle / Ivy

There is a newer version: 5.12.0
Show newest version
/*
 * Copyright (c) 2007 Mockito contributors
 * This program is made available under the terms of the MIT License.
 */
package org.mockito.internal.stubbing.defaultanswers;

import java.io.Serializable;

import org.mockito.Mockito;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.util.MockUtil;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.mock.MockCreationSettings;
import org.mockito.stubbing.Answer;

public class ReturnsMocks implements Answer, Serializable {

    private static final long serialVersionUID = -6755257986994634579L;
    private final Answer delegate = new ReturnsMoreEmptyValues();

    @Override
    public Object answer(final InvocationOnMock invocation) throws Throwable {
        Object defaultReturnValue = delegate.answer(invocation);

        if (defaultReturnValue != null) {
            return defaultReturnValue;
        }

        return RetrieveGenericsForDefaultAnswers.returnTypeForMockWithCorrectGenerics(
                invocation,
                new RetrieveGenericsForDefaultAnswers.AnswerCallback() {
                    @Override
                    public Object apply(Class type) {
                        if (type == null) {
                            return null;
                        }

                        MockCreationSettings mockSettings =
                                MockUtil.getMockSettings(invocation.getMock());

                        return Mockito.mock(
                                type,
                                new MockSettingsImpl<>()
                                        .defaultAnswer(ReturnsMocks.this)
                                        .mockMaker(mockSettings.getMockMaker()));
                    }
                });
    }
}