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

com.fitbur.mockito.internal.stubbing.answers.ThrowsExceptionClass Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
/*
 * Copyright (c) 2007 Mockito contributors
 * This program is made available under the terms of the MIT License.
 */

package com.fitbur.mockito.internal.stubbing.answers;

import com.fitbur.mockito.exceptions.Reporter;
import com.fitbur.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
import com.fitbur.mockito.invocation.InvocationOnMock;
import com.fitbur.mockito.stubbing.Answer;
import com.fitbur.mockito.objenesis.ObjenesisHelper;

import static com.fitbur.mockito.exceptions.Reporter.notAnException;

import java.io.Serializable;

public class ThrowsExceptionClass implements Answer, Serializable {

    private final Class throwableClass;
    private final ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter();

    public ThrowsExceptionClass(Class throwableClass) {
        this.throwableClass = checkNonNullThrowable(throwableClass);
    }

    private Class checkNonNullThrowable(Class throwableClass) {
        if(throwableClass == null || !Throwable.class.isAssignableFrom(throwableClass)) {
            throw notAnException();
        }
        return throwableClass;
    }

    public Object answer(InvocationOnMock invocation) throws Throwable {
        //TODO centralize the use of Objenesis. Why do we use ObjenesisHelper?
        Throwable throwable = (Throwable) ObjenesisHelper.newInstance(throwableClass);
        throwable.fillInStackTrace();
        filter.filter(throwable);
        throw throwable;
    }

    public Class getThrowableClass() {
        return throwableClass;
    }
}