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

name.remal.mockito.StrictMockito Maven / Gradle / Ivy

The newest version!
package name.remal.mockito;

import org.jetbrains.annotations.NotNull;
import org.mockito.Mockito;

import static java.lang.System.identityHashCode;

public class StrictMockito extends Mockito {

    @FunctionalInterface
    interface StrictMockConfigurer {
        void configure(T mock) throws Throwable;
    }

    public  T strictMock(@NotNull Class classToMock, @NotNull StrictMockConfigurer configurer) {
        StrictMockAnswer defaultAnswer = new StrictMockAnswer();
        T mock = mock(classToMock, defaultAnswer);

        // We want toString() to be stubbed be default:
        when(mock.toString()).thenReturn(classToMock.getSimpleName() + "@" + identityHashCode(mock));

        try {
            configurer.configure(mock);
        } catch (Throwable throwable) {
            throw sneakyThrow(throwable);
        }

        defaultAnswer.setEnabled(true);

        return mock;
    }

    @NotNull
    private static RuntimeException sneakyThrow(@NotNull Throwable t) {
        StrictMockito.sneakyThrow0(t);
        return null;
    }

    @SuppressWarnings("unchecked")
    private static  void sneakyThrow0(Throwable t) throws T {
        throw (T) t;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy