org.mockito.exceptions.base.MockitoException Java Examples

The following examples show how to use org.mockito.exceptions.base.MockitoException. 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
Source File: ConcurrentCompositeLineConsumerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
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 File: IOOBExceptionShouldNotBeThrownWhenNotCodingFluentlyTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@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 #3
Source File: RunnerFactoryTest.java    From astor with 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 #4
Source File: ClassPathLoader.java    From astor with 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 File: GenericMetadataSupport.java    From astor with 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 File: StubbingUsingDoReturnTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldNotAllowDoNothingOnNonVoids() {
    try {
        doNothing().when(mock).simpleMethod();
        fail();
    } catch (MockitoException e) {
        assertContains("Only void methods can doNothing()", e.getMessage());
    }
}
 
Example #7
Source File: RestrictedObjectMethodsTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldScreamWhenVerifyToString() {
    try {
        verify(mock).toString();
        fail();
    } catch (MockitoException e) {
        assertContains("cannot verify", e.getMessage());
    }
}
 
Example #8
Source File: VerificationInOrderWithCallsTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldFailToCreateCallsForNonInOrderVerification(){
    // Given
    mockOne.voidMethod();
    exceptionRule.expect( MockitoException.class );
    exceptionRule.expectMessage( "calls is only intended to work with InOrder" );

    // When
    verify( mockOne, calls(1)).voidMethod();

    // Then - expected exception thrown
}
 
Example #9
Source File: StubbingWithExtraAnswersTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldScreamWhenNullPassed() throws Exception {
    try {
        //when
        new ReturnsElementsOf(null);
        //then
        fail();
    } catch (MockitoException e) {}
}
 
Example #10
Source File: MockingMultipleInterfacesTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldScreamWhenTheSameInterfacesPassed() {
    try {
        //when
        mock(IMethods.class, withSettings().extraInterfaces(IMethods.class));
        fail();
    } catch (MockitoException e) {
        //then
        assertContains("You mocked following type: IMethods", e.getMessage());
    }
}
 
Example #11
Source File: SpyingOnInterfacesTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldFailFastWhenCallingRealMethodOnInterface() throws Exception {
    List list = mock(List.class);
    try {
        //when
        when(list.get(0)).thenCallRealMethod();
        //then
        fail();
    } catch (MockitoException e) {}
}
 
Example #12
Source File: StackTraceFilteringTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldFilterStacktraceOnMockitoException() {
    verify(mock);
    try {
        verify(mock).oneArg(true); 
        fail();
    } catch (MockitoException expected) {
        assertThat(expected, hasFirstMethodInStackTrace("shouldFilterStacktraceOnMockitoException"));
    }
}
 
Example #13
Source File: AnswersValidatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_validate_null_throwable() throws Throwable {
    try {
        validator.validate(new ThrowsException(null), new InvocationBuilder().toInvocation());
        fail();
    } catch (MockitoException e) {}
}
 
Example #14
Source File: StubbingConsecutiveAnswersTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldValidateConsecutiveExceptionForVoidMethod() throws Exception {
    stubVoid(mock)
        .toReturn()
        .toThrow(new Exception())
        .on().voidMethod();
}
 
Example #15
Source File: Reporter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void cannotInjectDependency(Field field, Object matchingMock, Exception details) {
    throw new MockitoException(join(
            "Mockito couldn't inject mock dependency '" + new MockUtil().getMockName(matchingMock) + "' on field ",
            "'" + field + "'",
            "whose type '" + field.getDeclaringClass().getCanonicalName() + "' was annotated by @InjectMocks in your test.",
            "Also I failed because: " + details.getCause().getMessage(),
            ""
    ), details);
}
 
Example #16
Source File: MockingProgressImplTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldCheckIfVerificationWasFinished() throws Exception {
    mockingProgress.verificationStarted(VerificationModeFactory.atLeastOnce());
    try {
        mockingProgress.verificationStarted(VerificationModeFactory.atLeastOnce());
        fail();
    } catch (MockitoException e) {}
}
 
Example #17
Source File: CaptorAnnotationTest.java    From astor with 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 #18
Source File: CapturingArgumentsTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldSaySomethingSmartWhenMisused() {
    ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
    try {
        argument.getValue();
        fail();
    } catch (MockitoException e) {}
}
 
Example #19
Source File: Reporter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public int invalidArgumentPositionRangeAtInvocationTime(InvocationOnMock invocation, boolean willReturnLastParameter, int argumentIndex) {
    throw new MockitoException(
            join("Invalid argument index for the current invocation of method : ",
                    " -> " + new MockUtil().getMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",
                    "",
                    (willReturnLastParameter ?
                            "Last parameter wanted" :
                            "Wanted parameter at position " + argumentIndex) + " but " + possibleArgumentTypesOf(invocation),
                    "The index need to be a positive number that indicates a valid position of the argument in the invocation.",
                    "However it is possible to use the -1 value to indicates that the last argument should be returned.",
                    ""));
}
 
Example #20
Source File: MocksSerializationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_fail_when_serializable_used_with_type_that_dont_implements_Serializable_and_dont_declare_a_no_arg_constructor() throws Exception {
    try {
        serializeAndBack(mock(NotSerializableAndNoDefaultConstructor.class, withSettings().serializable()));
        fail("should have thrown an exception to say the object is not serializable");
    } catch (MockitoException e) {
        Assertions.assertThat(e.getMessage())
                .contains(NotSerializableAndNoDefaultConstructor.class.getSimpleName())
                .contains("serializable()")
                .contains("implement Serializable")
                .contains("no-arg constructor");
    }
}
 
Example #21
Source File: MockitoStubberTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldFinishStubbingWhenWrongThrowableIsSet() throws Exception {
    state.stubbingStarted();
    try {
        invocationContainerImpl.addAnswer(new ThrowsException(new Exception()));
        fail();
    } catch (MockitoException e) {
        state.validateState();
    }
}
 
Example #22
Source File: AtMostXVerificationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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 #23
Source File: FieldReader.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public Object read() {
    try {
        return field.get(target);
    } catch (Exception e) {
        throw new MockitoException("Cannot read state from field: " + field + ", on instance: " + target);
    }
}
 
Example #24
Source File: ArgumentsExtractorVerifier.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void verify(final VerificationData data) {
    List<Invocation> actualInvocations =
        InvocationsFinder.findInvocations(data.getAllInvocations(), data.getTarget());
    if (actualInvocations.size() != 1) {
        throw new MockitoException("This verifier can only be used with 1 invocation, got "
                + actualInvocations.size());
    }
    Invocation invocation = actualInvocations.get(0);
    arguments = invocation.getArguments();
    invocation.markVerified();
}
 
Example #25
Source File: ParameterizedConstructorInstantiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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");
    }
}
 
Example #26
Source File: MockingMultipleInterfacesTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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 #27
Source File: ParameterizedConstructorInstantiatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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 #28
Source File: VarargCapturingMatcherTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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 #29
Source File: CglibMockMaker.java    From astor with 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 #30
Source File: TimesTest.java    From astor with 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());
    }
}