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

guru.mocker.java.internal.api.WhenMockerImpl Maven / Gradle / Ivy

The newest version!
package guru.mocker.java.internal.api;

import guru.mocker.java.api.MockerContext;
import guru.mocker.java.api.ThenMocker;
import guru.mocker.java.api.WhenMocker;
import guru.mocker.java.internal.CallableMethod;
import guru.mocker.java.internal.result.ComparableResult;
import guru.mocker.java.internal.result.Either;
import guru.mocker.java.internal.result.ExceptionResult;
import guru.mocker.java.internal.result.ValidResult;

import java.util.concurrent.Callable;

public class WhenMockerImpl implements WhenMocker
{
    private final MockerContext mockerContext;

    public WhenMockerImpl(MockerContext mockerContext)
    {
        this.mockerContext = mockerContext;
    }

    @Override
    public ThenMocker whenCalled()
    {
        prepareReal();

        executeMethod();

        return mockerContext.mockerFactory().createThenMocker(mockerContext);
    }

    private void executeMethod()
    {
        for (CallableMethod method : mockerContext.methods())
            storeResultOfMethodCalls(method);
    }

    private void prepareReal()
    {
        for(Runnable realGivens: mockerContext.realGivens())
            realGivens.run();
    }

    private void storeResultOfMethodCalls(CallableMethod method)
    {

        mockerContext.comparableResults().add(
                new ComparableResult(
                        callMethod(method.mockMethod()),
                        callMethod(method.realMethod())
                ));
    }

    private Either callMethod(Callable method)
    {
        Either result;
        try {
            result = Either.left(new ValidResult(method.call()));
        }
        catch (Throwable throwable) {
            result = Either.right(new ExceptionResult(throwable));
        }
        return result;
    }
}