org.mockito.InjectMocks#org.mockito.exceptions.base.MockitoException源码实例Demo

下面列出了org.mockito.InjectMocks#org.mockito.exceptions.base.MockitoException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: che   文件: ConcurrentCompositeLineConsumerTest.java
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);
  }
}
 
源代码2 项目: astor   文件: RunnerFactoryTest.java
@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());
    }
}
 
@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());
    }
}
 
源代码4 项目: astor   文件: ClassPathLoader.java
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);
    }
}
 
源代码5 项目: astor   文件: GenericMetadataSupport.java
/**
 * 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);
}
 
源代码6 项目: nakadi   文件: EventStreamControllerTest.java
@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);
}
 
源代码7 项目: astor   文件: StubbingWithExtraAnswersTest.java
@Test
public void shouldScreamWhenNullPassed() throws Exception {
    try {
        //when
        new ReturnsElementsOf(null);
        //then
        fail();
    } catch (MockitoException e) {}
}
 
源代码8 项目: astor   文件: FieldInitializerTest.java
@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());
    }
}
 
源代码9 项目: astor   文件: Reporter.java
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);"
            ));
}
 
源代码10 项目: astor   文件: Reporter.java
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();"
            ));
}
 
源代码11 项目: astor   文件: Reporter.java
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"
         ));
}
 
源代码12 项目: astor   文件: CaptorAnnotationProcessor.java
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);
}
 
源代码13 项目: astor   文件: Reporter.java
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()<- );"
    ));
}
 
源代码14 项目: astor   文件: AnswersValidatorTest.java
@Test
public void shouldValidateNullThrowable() throws Throwable {
    try {
        validator.validate(new ThrowsException(null), null);
        fail();
    } catch (MockitoException e) {}
}
 
源代码15 项目: astor   文件: Reporter.java
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."
    ));
}
 
源代码16 项目: astor   文件: Reporter.java
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"
    ));
}
 
源代码17 项目: astor   文件: TimesTest.java
@Test
public void shouldNotAllowNegativeNumberOfInvocations() throws Exception {
    try {
        VerificationModeFactory.times(-50);
        fail();
    } catch (MockitoException e) {
        assertEquals("Negative value is not allowed here", e.getMessage());
    }
}
 
源代码18 项目: astor   文件: MockingMultipleInterfacesTest.java
@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");
    }
}
 
源代码19 项目: astor   文件: Reporter.java
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.",
            ""
    ));
}
 
源代码20 项目: astor   文件: AtMostXVerificationTest.java
@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());
    }
}
 
源代码21 项目: astor   文件: StackTraceFilteringTest.java
@Test
public void shouldFilterStacktraceWhenInOrderThrowsMockitoException() {
    try {
        inOrder();
        fail();
    } catch (MockitoException expected) {
        assertThat(expected, hasFirstMethodInStackTrace("shouldFilterStacktraceWhenInOrderThrowsMockitoException"));
    }
}
 
源代码22 项目: astor   文件: MockingMultipleInterfacesTest.java
@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());
    }
}
 
源代码23 项目: astor   文件: DefaultAnnotationEngine.java
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);    
}
 
源代码24 项目: astor   文件: Reporter.java
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"
    ));
}
 
源代码25 项目: astor   文件: CaptorAnnotationTest.java
@Test
public void shouldScreamWhenMoreThanOneMockitoAnnotaton() {
    try {
        MockitoAnnotations.initMocks(new ToManyAnnotations());
        fail();
    } catch (MockitoException e) {
        assertContains("missingGenericsField", e.getMessage());
        assertContains("multiple Mockito annotations", e.getMessage());            
    }
}
 
源代码26 项目: astor   文件: CglibMockMaker.java
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;
}
 
源代码27 项目: astor   文件: VarargCapturingMatcherTest.java
@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) {}
}
 
@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");
    }
}
 
源代码29 项目: astor   文件: MockingMultipleInterfacesTest.java
@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");
    }
}
 
@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");
    }
}