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

com.bluecatcode.mockito.stubbing.AnswerWith Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package com.bluecatcode.mockito.stubbing;

import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
import org.mockito.internal.util.MockUtil;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import javax.annotation.Nullable;
import java.util.LinkedList;

/**
 * Mockito {@link Answer} with multiple throwables and then return values,
 * e.g. given(...).will(answerWith(..., ...)
 * @param  the answer type
 */
public class AnswerWith implements Answer {

    private final ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter();

    private final Iterable throwables;
    private final Iterable values;

    public AnswerWith(Iterable throwables, Iterable returnValues) {
        if (throwables == null) {
            throw new MockitoException("AnswerWith does not accept null as constructor argument.\n" +
                    "Please pass throwables, can be empty");
        }
        if (returnValues == null) {
            throw new MockitoException("AnswerWith does not accept null as constructor argument.\n" +
                    "Please pass return values, can be empty");
        }
        this.throwables = throwables;
        this.values = returnValues;
    }

    public static  AnswerWith answerWith(Iterable throwables, Iterable returnValues) {
        return new AnswerWith(throwables, returnValues);
    }

    public static  AnswerWith answerWith(Iterable throwables) {
        return new AnswerWith(throwables, new LinkedList<>());
    }

    @Nullable
    public T answer(InvocationOnMock invocation) throws Throwable {
        if (throwables.iterator().hasNext()) {
            Throwable throwable = throwables.iterator().next();
            if (new MockUtil().isMock(throwable)) {
                throw throwable;
            }
            Throwable t = throwable.fillInStackTrace();
            filter.filter(t);
            throw t;
        }
        if (values.iterator().hasNext()) {
            return values.iterator().next();
        } else {
            return null;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy