Java Code Examples for org.mockito.exceptions.base.MockitoException

The following examples show how to use org.mockito.exceptions.base.MockitoException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public void verify(VerificationData verificationData) {
  List<Invocation> invocations = verificationData.getAllInvocations();
  InvocationMatcher invocationMatcher = verificationData.getWanted();

  if (invocations == null || invocations.isEmpty()) {
    throw new MockitoException(
        "\nNo interactions with "
            + invocationMatcher.getInvocation().getMock()
            + " mock so far");
  }
  Invocation invocation = invocations.get(invocations.size() - 1);

  if (!invocationMatcher.matches(invocation)) {
    throw new MockitoException("\nWanted but not invoked:\n" + invocationMatcher);
  }
}
 
Example 2
Source Project: astor   Source File: RunnerFactoryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void
shouldThrowMeaningfulMockitoExceptionIfNoValidJUnitFound()  throws Exception{
    //given
    RunnerProvider provider = new RunnerProvider() {
        public boolean isJUnit45OrHigherAvailable() {
            return false;
        }
        public RunnerImpl newInstance(String runnerClassName, Class<?> constructorParam) throws Exception {
            throw new InitializationError("Where is JUnit, dude?");
        }
    };
    RunnerFactory factory = new RunnerFactory(provider);
    
    try {
        //when
        factory.create(RunnerFactoryTest.class);
        fail();
    } catch (MockitoException e) {
        //then
        assertContains("upgrade your JUnit version", e.getMessage());
    }
}
 
Example 3
@Test
public void second_stubbing_throws_IndexOutOfBoundsException() throws Exception {
    Map<String, String> map = mock(Map.class);

    OngoingStubbing<String> mapOngoingStubbing = when(map.get(anyString()));

    mapOngoingStubbing.thenReturn("first stubbing");

    try {
        mapOngoingStubbing.thenReturn("second stubbing");
        fail();
    } catch (MockitoException e) {
        assertThat(e.getMessage())
                .contains("Incorrect use of API detected here")
                .contains(this.getClass().getSimpleName());
    }
}
 
Example 4
Source Project: astor   Source File: ClassPathLoader.java    License: GNU General Public License v2.0 6 votes vote down vote up
static <T> T findPluginImplementation(Class<T> pluginType, String defaultPluginClassName) {
    for (T plugin : loadImplementations(pluginType)) {
        return plugin; // return the first one service loader finds (if any)
    }

    try {
        // Default implementation. Use our own ClassLoader instead of the context
        // ClassLoader, as the default implementation is assumed to be part of
        // Mockito and may not be available via the context ClassLoader.
        return pluginType.cast(Class.forName(defaultPluginClassName).newInstance());
    } catch (Exception e) {
        throw new MockitoException("Internal problem occurred, please report it. " +
                "Mockito is unable to load the default implementation of class that is a part of Mockito distribution. " +
                "Failed to load " + pluginType, e);
    }
}
 
Example 5
Source Project: astor   Source File: GenericMetadataSupport.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Resolve current method generic return type to a {@link GenericMetadataSupport}.
 *
 * @param method Method to resolve the return type.
 * @return {@link GenericMetadataSupport} representing this generic return type.
 */
public GenericMetadataSupport resolveGenericReturnType(Method method) {
    Type genericReturnType = method.getGenericReturnType();
    // logger.log("Method '" + method.toGenericString() + "' has return type : " + genericReturnType.getClass().getInterfaces()[0].getSimpleName() + " : " + genericReturnType);

    if (genericReturnType instanceof Class) {
        return new NotGenericReturnTypeSupport(genericReturnType);
    }
    if (genericReturnType instanceof ParameterizedType) {
        return new ParameterizedReturnType(this, method.getTypeParameters(), (ParameterizedType) method.getGenericReturnType());
    }
    if (genericReturnType instanceof TypeVariable) {
        return new TypeVariableReturnType(this, method.getTypeParameters(), (TypeVariable) genericReturnType);
    }

    throw new MockitoException("Ouch, it shouldn't happen, type '" + genericReturnType.getClass().getCanonicalName() + "' on method : '" + method.toGenericString() + "' is not supported : " + genericReturnType);
}
 
Example 6
Source Project: nakadi   Source File: EventStreamControllerTest.java    License: MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void whenNoParamsThenDefaultsAreUsed() throws Exception {
    final ArgumentCaptor<EventStreamConfig> configCaptor = ArgumentCaptor.forClass(EventStreamConfig.class);

    final EventConsumer.LowLevelConsumer eventConsumerMock = mock(EventConsumer.LowLevelConsumer.class);
    when(topicRepositoryMock.createEventConsumer(
            any(), any()))
            .thenReturn(eventConsumerMock);

    final EventStream eventStreamMock = mock(EventStream.class);
    when(eventStreamFactoryMock.createEventStream(any(), any(), configCaptor.capture(), any()))
            .thenReturn(eventStreamMock);

    when(eventTypeCache.getEventType(TEST_EVENT_TYPE_NAME)).thenReturn(EVENT_TYPE);

    mockMvc.perform(
            get(String.format("/event-types/%s/events", TEST_EVENT_TYPE_NAME))
                    .header("X-nakadi-cursors", "[{\"partition\":\"0\",\"offset\":\"000000000000000000\"}]"))
            .andExpect(status().isOk());

    // we have to retry here as mockMvc exits at the very beginning, before the body starts streaming
    waitFor(() -> {
        final EventStreamConfig actualConfig = configCaptor.getValue();

        assertThat(actualConfig.getBatchLimit(), equalTo(1));
        assertThat(actualConfig.getBatchTimeout(), equalTo(30));
        assertThat(actualConfig.getCursors(),
                equalTo(ImmutableList.of(NakadiCursor.of(timeline, "0", "000000000000000000"))));
        assertThat(actualConfig.getStreamKeepAliveLimit(), equalTo(0));
        assertThat(actualConfig.getStreamLimit(), equalTo(0));
        assertThat(actualConfig.getStreamTimeout(),
                greaterThanOrEqualTo(EventStreamConfig.MAX_STREAM_TIMEOUT - 1200));
        assertThat(actualConfig.getStreamTimeout(),
                lessThanOrEqualTo(EventStreamConfig.MAX_STREAM_TIMEOUT));
    }, 2000, 50, MockitoException.class);
}
 
Example 7
@Test
public void shouldScreamWhenNullPassed() throws Exception {
    try {
        //when
        new ReturnsElementsOf(null);
        //then
        fail();
    } catch (MockitoException e) {}
}
 
Example 8
Source Project: astor   Source File: FieldInitializerTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_fail_to_instantiate_field_if_default_constructor_throws_exception() throws Exception {
    FieldInitializer fieldInitializer = new FieldInitializer(this, field("throwingExDefaultConstructor"));
    try {
        fieldInitializer.initialize();
        fail();
    } catch (MockitoException e) {
        InvocationTargetException ite = (InvocationTargetException) e.getCause();
        assertTrue(ite.getTargetException() instanceof NullPointerException);
        assertEquals("business logic failed", ite.getTargetException().getMessage());
    }
}
 
Example 9
Source Project: astor   Source File: Reporter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void mocksHaveToBePassedWhenCreatingInOrder() {
    throw new MockitoException(join(
            "Method requires argument(s)!",
            "Pass mocks that require verification in order.",
            "For example:",
            "    InOrder inOrder = inOrder(mockOne, mockTwo);"
            ));
}
 
Example 10
Source Project: astor   Source File: Reporter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void inOrderRequiresFamiliarMock() {
    throw new MockitoException(join(
            "InOrder can only verify mocks that were passed in during creation of InOrder.",
            "For example:",
            "    InOrder inOrder = inOrder(mockOne);",
            "    inOrder.verify(mockOne).doStuff();"
            ));
}
 
Example 11
Source Project: astor   Source File: Reporter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void onlyVoidMethodsCanBeSetToDoNothing() {
    throw new MockitoException(join(
            "Only void methods can doNothing()!",
            "Example of correct use of doNothing():",
            "    doNothing().",
            "    doThrow(new RuntimeException())",
            "    .when(mock).someVoidMethod();",
            "Above means:",
            "someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called"
         ));
}
 
Example 12
public Object process(Captor annotation, Field field) {
    Class<?> type = field.getType();
    if (!ArgumentCaptor.class.isAssignableFrom(type)) {
        throw new MockitoException("@Captor field must be of the type ArgumentCaptor.\n" + "Field: '"
           + field.getName() + "' has wrong type\n"
           + "For info how to use @Captor annotations see examples in javadoc for MockitoAnnotations class.");
    }
    Class cls = new GenericMaster().getGenericType(field);
    return ArgumentCaptor.forClass(cls);
}
 
Example 13
Source Project: astor   Source File: Reporter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void mockedTypeIsInconsistentWithSpiedInstanceType(Class<?> mockedType, Object spiedInstance) {
    throw new MockitoException(join(
            "Mocked type must be the same as the type of your spied instance.",
            "Mocked type must be: " + spiedInstance.getClass().getSimpleName() + ", but is: " + mockedType.getSimpleName(),
            "  //correct spying:",
            "  spy = mock( ->ArrayList.class<- , withSettings().spiedInstance( ->new ArrayList()<- );",
            "  //incorrect - types don't match:",
            "  spy = mock( ->List.class<- , withSettings().spiedInstance( ->new ArrayList()<- );"
    ));
}
 
Example 14
Source Project: astor   Source File: AnswersValidatorTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldValidateNullThrowable() throws Throwable {
    try {
        validator.validate(new ThrowsException(null), null);
        fail();
    } catch (MockitoException e) {}
}
 
Example 15
Source Project: astor   Source File: Reporter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void cannotVerifyToString() {
    throw new MockitoException(join(
            "Mockito cannot verify toString()",
            "toString() is too often used behind of scenes  (i.e. during String concatenation, in IDE debugging views). " +
                    "Verifying it may give inconsistent or hard to understand results. " +
                    "Not to mention that verifying toString() most likely hints awkward design (hard to explain in a short exception message. Trust me...)",
            "However, it is possible to stub toString(). Stubbing toString() smells a bit funny but there are rare, legitimate use cases."
    ));
}
 
Example 16
Source Project: astor   Source File: Reporter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void onlyVoidMethodsCanBeSetToDoNothing() {
    throw new MockitoException(join(
            "Only void methods can doNothing()!",
            "Example of correct use of doNothing():",
            "    doNothing().",
            "    doThrow(new RuntimeException())",
            "    .when(mock).someVoidMethod();",
            "Above means:",
            "someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called"
    ));
}
 
Example 17
Source Project: astor   Source File: TimesTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldNotAllowNegativeNumberOfInvocations() throws Exception {
    try {
        VerificationModeFactory.times(-50);
        fail();
    } catch (MockitoException e) {
        assertEquals("Negative value is not allowed here", e.getMessage());
    }
}
 
Example 18
@Test
public void should_scream_when_null_passed_instead_of_an_array() {
    try {
        //when
        mock(Foo.class, withSettings().extraInterfaces((Class[]) null));
        fail();
    } catch (MockitoException e) {
        //then
        assertThat(e.getMessage()).contains("extraInterfaces() requires at least one interface");
    }
}
 
Example 19
Source Project: astor   Source File: Reporter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void serializableWontWorkForObjectsThatDontImplementSerializable(Class classToMock) {
    throw new MockitoException(join(
            "You are using the setting 'withSettings().serializable()' however the type you are trying to mock '" + classToMock.getSimpleName() + "'",
            "do not implement Serializable AND do not have a no-arg constructor.",
            "This combination is requested, otherwise you will get an 'java.io.InvalidClassException' when the mock will be serialized",
            "",
            "Also note that as requested by the Java serialization specification, the whole hierarchy need to implements Serializable,",
            "i.e. the top-most superclass has to implements Serializable.",
            ""
    ));
}
 
Example 20
@Test
public void shouldNotAllowNegativeNumber() throws Exception {
    try {
        verify(mock, atMost(-1)).clear();
        fail();
    } catch (MockitoException e) {
        assertEquals("Negative value is not allowed here", e.getMessage());
    }
}
 
Example 21
@Test
public void shouldFilterStacktraceWhenInOrderThrowsMockitoException() {
    try {
        inOrder();
        fail();
    } catch (MockitoException expected) {
        assertThat(expected, hasFirstMethodInStackTrace("shouldFilterStacktraceWhenInOrderThrowsMockitoException"));
    }
}
 
Example 22
@Test
public void shouldScreamWhenNoArgsPassed() {
    try {
        //when
        mock(Foo.class, withSettings().extraInterfaces());
        fail();
    } catch (MockitoException e) {
        //then
        assertContains("extraInterfaces() requires at least one interface", e.getMessage());
    }
}
 
Example 23
private Object processAnnotationOn(Captor annotation, Field field) {
    Class<?> type = field.getType();
    if (!ArgumentCaptor.class.isAssignableFrom(type)) {
        throw new MockitoException("@Captor field must be of the type ArgumentCaptor.\n" + "Field: '"
                + field.getName() + "' has wrong type\n"
                + "For info how to use @Captor annotations see examples in javadoc for MockitoAnnotations class.");
    }
    Class cls = new GenericMaster().getGenericType(field);        
    return ArgumentCaptor.forClass(cls);    
}
 
Example 24
Source Project: astor   Source File: Reporter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void cannotMockFinalClass(Class<?> clazz) {
    throw new MockitoException(join(
            "Cannot mock/spy " + clazz.toString(),
            "Mockito cannot mock/spy following:",
            "  - final classes",
            "  - anonymous classes",
            "  - primitive types"
    ));
}
 
Example 25
Source Project: astor   Source File: CaptorAnnotationTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldScreamWhenMoreThanOneMockitoAnnotaton() {
    try {
        MockitoAnnotations.initMocks(new ToManyAnnotations());
        fail();
    } catch (MockitoException e) {
        assertContains("missingGenericsField", e.getMessage());
        assertContains("multiple Mockito annotations", e.getMessage());            
    }
}
 
Example 26
Source Project: astor   Source File: CglibMockMaker.java    License: GNU General Public License v2.0 5 votes vote down vote up
private InternalMockHandler cast(MockHandler handler) {
    if (!(handler instanceof InternalMockHandler)) {
        throw new MockitoException("At the moment you cannot provide own implementations of MockHandler." +
                "\nPlease see the javadocs for the MockMaker interface.");
    }
    return (InternalMockHandler) handler;
}
 
Example 27
@Test
public void should_scream_when_nothing_yet_captured() throws Exception {
    //given
    VarargCapturingMatcher m = new VarargCapturingMatcher();

    try {
        //when
        m.getLastVarargs();
        //then
        fail();
    } catch (MockitoException e) {}
}
 
Example 28
@Test
public void should_report_failure_if_constructor_throws_exception() throws Exception {
    given(resolver.resolveTypeInstances(Matchers.<Class<?>[]>anyVararg())).willReturn(new Object[]{ null });

    try {
        new ParameterizedConstructorInstantiator(this, field("withThrowingConstructor"), resolver).instantiate();
        fail();
    } catch (MockitoException e) {
        assertThat(e.getMessage()).contains("constructor").contains("raised an exception");
    }
}
 
Example 29
@Test
public void should_scream_when_non_interface_passed() {
    try {
        //when
        mock(Foo.class, withSettings().extraInterfaces(Foo.class));
        fail();
    } catch (MockitoException e) {
        //then
        assertThat(e.getMessage()).contains("Foo which is not an interface");
    }
}
 
Example 30
@Test
public void should_fail_if_no_parameterized_constructor_found___excluding_inner_and_others_kind_of_types() throws Exception {
    try {
        new ParameterizedConstructorInstantiator(this, field("withNoArgConstructor"), resolver).instantiate();
        fail();
    } catch (MockitoException me) {
        assertThat(me.getMessage()).contains("no parameterized constructor").contains("withNoArgConstructor").contains("NoArgConstructor");
    }
}