private void checkAttribute(final Function<UserOrgEditionVo, String> function, final String value) { // Check LDAP Mockito.verify(task.resource, new DefaultVerificationMode(data -> { if (data.getAllInvocations().size() != 2) { throw new MockitoException("Expect two calls"); } // "findBy" call Assert.assertEquals(DEFAULT_USER, data.getAllInvocations().get(0).getArguments()[0]); // "update" call final UserOrgEditionVo userLdap = (UserOrgEditionVo) data.getAllInvocations().get(1).getArguments()[0]; Assert.assertNotNull(userLdap); Assert.assertEquals(value, function.apply(userLdap)); })).update(null); }
public <T> T imposterise(final MethodInterceptor interceptor, Class<T> mockedType, Class<?>... ancillaryTypes) { Class<Factory> proxyClass = null; Object proxyInstance = null; try { setConstructorsAccessible(mockedType, true); proxyClass = createProxyClass(mockedType, ancillaryTypes); proxyInstance = createProxy(proxyClass, interceptor); return mockedType.cast(proxyInstance); } catch (ClassCastException cce) { throw new MockitoException(join( "ClassCastException occurred while creating the mockito proxy :", " class to mock : " + describeClass(mockedType), " created class : " + describeClass(proxyClass), " proxy instance class : " + describeClass(proxyInstance), " instance creation by : " + instantiator.getClass().getSimpleName(), "", "You might experience classloading issues, disabling the Objenesis cache *might* help (see MockitoConfiguration)" ), cce); } finally { setConstructorsAccessible(mockedType, false); } }
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); } }
public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) { if(mocks.size() == 1) { final Object matchingMock = mocks.iterator().next(); return new OngoingInjecter() { public boolean thenInject() { try { if (!new BeanPropertySetter(fieldInstance, field).set(matchingMock)) { new FieldSetter(fieldInstance, field).set(matchingMock); } } catch (Exception e) { throw new MockitoException("Problems injecting dependency in " + field.getName(), e); } return true; } }; } return new OngoingInjecter() { public boolean thenInject() { return false; } }; }
private static Set<Object> scanMocks(Object testClass, Class<?> clazz) { Set<Object> mocks = new HashSet<Object>(); for (Field field : clazz.getDeclaredFields()) { // mock or spies only if (null != field.getAnnotation(Spy.class) || null != field.getAnnotation(org.mockito.Mock.class) || null != field.getAnnotation(Mock.class)) { Object fieldInstance = null; boolean wasAccessible = field.isAccessible(); field.setAccessible(true); try { fieldInstance = field.get(testClass); } catch (IllegalAccessException e) { throw new MockitoException("Problems injecting dependencies in " + field.getName(), e); } finally { field.setAccessible(wasAccessible); } if (fieldInstance != null) { mocks.add(fieldInstance); } } } return mocks; }
/** * Initializes objects annotated with Mockito annotations for given testClass: * @{@link org.mockito.Mock}, @{@link Spy}, @{@link Captor}, @{@link InjectMocks} * <p> * See examples in javadoc for {@link MockitoAnnotations} class. */ public static void initMocks(Object testClass) { if (testClass == null) { throw new MockitoException("testClass cannot be null. For info how to use @Mock annotations see examples in javadoc for MockitoAnnotations class"); } AnnotationEngine annotationEngine = new GlobalConfiguration().getAnnotationEngine(); Class<?> clazz = testClass.getClass(); //below can be removed later, when we get read rid of deprecated stuff if (annotationEngine.getClass() != new DefaultMockitoConfiguration().getAnnotationEngine().getClass()) { //this means user has his own annotation engine and we have to respect that. //we will do annotation processing the old way so that we are backwards compatible while (clazz != Object.class) { scanDeprecatedWay(annotationEngine, testClass, clazz); clazz = clazz.getSuperclass(); } } //anyway act 'the new' way annotationEngine.process(testClass.getClass(), testClass); }
@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()); } }
public void process(Class<?> clazz, Object testInstance) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { boolean alreadyAssigned = false; for(Annotation annotation : field.getAnnotations()) { Object mock = createMockFor(annotation, field); if (mock != null) { throwIfAlreadyAssigned(field, alreadyAssigned); alreadyAssigned = true; try { new FieldSetter(testInstance, field).set(mock); } catch (Exception e) { throw new MockitoException("Problems setting field " + field.getName() + " annotated with " + annotation, e); } } } } }
@SuppressWarnings("deprecation") static void processAnnotationDeprecatedWay(AnnotationEngine annotationEngine, Object testClass, Field field) { boolean alreadyAssigned = false; for(Annotation annotation : field.getAnnotations()) { Object mock = annotationEngine.createMockFor(annotation, field); if (mock != null) { throwIfAlreadyAssigned(field, alreadyAssigned); alreadyAssigned = true; try { new FieldSetter(testClass, field).set(mock); } catch (Exception e) { throw new MockitoException("Problems setting field " + field.getName() + " annotated with " + annotation, e); } } } }
@Test public void full() throws IOException, InterruptedException { final BatchTaskVo<GroupImportEntry> importTask = full("Gfi France;Fonction"); // Check the result final GroupImportEntry importEntry = checkImportTask(importTask); Assert.assertEquals("Gfi France", importEntry.getName()); Assert.assertEquals("Fonction", importEntry.getType()); Assert.assertNull(importEntry.getDepartment()); Assert.assertNull(importEntry.getOwner()); Assert.assertNull(importEntry.getAssistant()); Assert.assertNull(importEntry.getParent()); Assert.assertTrue(importEntry.getStatus()); Assert.assertNull(importEntry.getStatusText()); // Check LDAP Mockito.verify(mockLdapResource, new DefaultVerificationMode(data -> { if (data.getAllInvocations().size() != 1) { throw new MockitoException("Expect one call"); } final GroupEditionVo group = (GroupEditionVo) data.getAllInvocations().get(0).getArguments()[0]; Assert.assertNotNull(group); Assert.assertEquals("Gfi France", group.getName()); Assert.assertNotNull(group.getScope()); Assert.assertTrue(group.getDepartments().isEmpty()); Assert.assertTrue(group.getOwners().isEmpty()); Assert.assertTrue(group.getAssistants().isEmpty()); Assert.assertNull(group.getParent()); })).create(null); }
@Test public void fullFull() throws IOException, InterruptedException { final BatchTaskVo<GroupImportEntry> importTask = full("Opérations Spéciales;Fonction;Operations;fdaugan,alongchu;jdoe5,wuser;700301,700302"); // Check the result final GroupImportEntry importEntry = checkImportTask(importTask); Assert.assertEquals("Opérations Spéciales", importEntry.getName()); Assert.assertEquals("Fonction", importEntry.getType()); Assert.assertEquals("Operations", importEntry.getParent()); Assert.assertEquals("fdaugan,alongchu", importEntry.getOwner()); Assert.assertEquals("jdoe5,wuser", importEntry.getAssistant()); Assert.assertEquals("700301,700302", importEntry.getDepartment()); Assert.assertTrue(importEntry.getStatus()); Assert.assertNull(importEntry.getStatusText()); // Check LDAP Mockito.verify(mockLdapResource, new DefaultVerificationMode(data -> { if (data.getAllInvocations().size() != 1) { throw new MockitoException("Expect one call"); } final GroupEditionVo group = (GroupEditionVo) data.getAllInvocations().get(0).getArguments()[0]; Assert.assertNotNull(group); Assert.assertEquals("Opérations Spéciales", group.getName()); Assert.assertNotNull(group.getScope()); Assert.assertEquals(2, group.getOwners().size()); Assert.assertEquals("fdaugan", group.getOwners().get(0)); Assert.assertEquals(2, group.getAssistants().size()); Assert.assertEquals("jdoe5", group.getAssistants().get(0)); Assert.assertEquals(2, group.getDepartments().size()); Assert.assertEquals("700301", group.getDepartments().get(0)); Assert.assertEquals("Operations", group.getParent()); })).create(null); }
@Before public void setup(){ mapper = (ObjectMapper) ReflectionTestUtils.getField(SpeechletRequestEnvelope.class, "OBJECT_MAPPER"); toTestQuery.calendarService = mock(CalendarService.class); try{ toTestBasic.speechService = spy(toTestBasic.speechService); toTestQuery.speechService = spy(toTestQuery.speechService); toTestNewEvent.speechService = spy(toTestNewEvent.speechService); }catch(MockitoException e){ //don't spy a spy... } }
private static Optional<DOMEntityOwnershipChange> getValueSafely(ArgumentCaptor<DOMEntityOwnershipChange> captor) { try { return Optional.fromNullable(captor.getValue()); } catch (MockitoException e) { // No value was captured return Optional.absent(); } }
@Test(expected = MockitoException.class) public void testExecuteWhenThrowingException() { mockToThrowException(); TestComplex .using(expectedConnection, LEAVE_OPEN) .withFirstInput(EXPECTED_FIRST_INPUT) .withSecondInput(EXPECTED_SECOND_INPUT) .execute(); }
@Test(expected = MockitoException.class) public void testForEachResultWhenThrowingException() { mockToThrowException(); TestComplex .using(expectedConnection, LEAVE_OPEN) .withFirstInput(EXPECTED_FIRST_INPUT) .withSecondInput(EXPECTED_SECOND_INPUT) .forEachResult(item -> {}); }
@Test(expected = MockitoException.class) public void testGetFirstResultWhenThrowingException() { mockToThrowException(); TestComplex .using(expectedConnection, LEAVE_OPEN) .withFirstInput(EXPECTED_FIRST_INPUT) .withSecondInput(EXPECTED_SECOND_INPUT) .getFirstResult(); }
public <T> T imposterise(final MethodInterceptor interceptor, Class<T> mockedType, Class<?>... ancillaryTypes) { try { setConstructorsAccessible(mockedType, true); Class<?> proxyClass = createProxyClass(mockedType, ancillaryTypes); return mockedType.cast(createProxy(proxyClass, interceptor)); } catch (ClassCastException cce) { throw new MockitoException(join( "ClassCastException occurred when creating the proxy.", "You might experience classloading issues, disabling the Objenesis cache *might* help (see MockitoConfiguration)" ), cce); } finally { setConstructorsAccessible(mockedType, false); } }
public static void notAnEnhancedClass() { throw new MockitoException(join( "Argument passed to initMock() is not an enhanced class!", "Example of correct using:", " StaticMockito.enhanceClass(\"package.NamedClass\");" )); }
public static void notAnInitializeEnhancedClass() { throw new MockitoException(join( "Argument passed to mocker() is an enhanced class, but not initialized!", "Example of correct using:", " StaticMockito.initMock(NamedClass.class);" )); }
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); }
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; }
private Object createProxy(Class<Factory> proxyClass, final MethodInterceptor interceptor) { Factory proxy; try { proxy = instantiator.newInstance(proxyClass); } catch (InstantiationException e) { throw new MockitoException("Unable to create mock instance of type '" + proxyClass.getSuperclass().getSimpleName() + "'", e); } proxy.setCallbacks(new Callback[] {interceptor, SerializableNoOp.SERIALIZABLE_INSTANCE }); return proxy; }
@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(eventTypeRepository.findByName(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 TestUtils.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); }
@Test public void shouldNotAllowNegativeNumberOfMinimumInvocations() throws Exception { try { VerificationModeFactory.atLeast(-50); fail(); } catch (MockitoException e) { assertEquals("Negative value is not allowed here", e.getMessage()); } }
public void mocksHaveToBePassedToVerifyNoMoreInteractions() { throw new MockitoException(join( "Method requires argument(s)!", "Pass mocks that should be verified, e.g:", " verifyNoMoreInteractions(mockOne, mockTwo);", " verifyZeroInteractions(mockOne, mockTwo);", "" )); }
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);" )); }
public RunnerImpl create(Class<?> klass) throws InvocationTargetException { try { if (runnerProvider.isJUnit45OrHigherAvailable()) { return runnerProvider.newInstance("org.mockito.internal.runners.JUnit45AndHigherRunnerImpl", klass); } else { return runnerProvider.newInstance("org.mockito.internal.runners.JUnit44RunnerImpl", klass); } } catch (InvocationTargetException e) { if (!new TestMethodsFinder().hasTestMethods(klass)) { throw new MockitoException( "\n" + "\n" + "No tests found in " + klass.getSimpleName() + "\n" + "Haven't you forgot @Test annotation?\n" , e); } throw e; } catch (Throwable t) { throw new MockitoException( "\n" + "\n" + "MockitoRunner can only be used with JUnit 4.4 or higher.\n" + "You can upgrade your JUnit version or write your own Runner (please consider contributing your runner to the Mockito community).\n" + "Bear in mind that you can still enjoy all features of the framework without using runners (they are completely optional).\n" + "If you get this error despite using JUnit 4.4 or higher then please report this error to the mockito mailing list.\n" , t); } }
@Test public void shouldFailIfCaptorHasWrongType() throws Exception { try { //when MockitoAnnotations.initMocks(this); fail(); } catch (MockitoException e) { //then assertContains("notACaptorField", e.getMessage()); assertContains("wrong type", e.getMessage()); } }
public void cannotStubVoidMethodWithAReturnValue(String methodName) { throw new MockitoException(join( "'" + methodName + "' is a *void method* and it *cannot* be stubbed with a *return value*!", "Voids are usually stubbed with Throwables:", " doThrow(exception).when(mock).someVoidMethod();", "If the method you are trying to stub is *overloaded* then make sure you are calling the right overloaded version.", "This exception might also occur when somewhere in your test you are stubbing *final methods*." )); }
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" )); }
@Test public void shouldFailToCreateCallsWithNegativeArgument(){ // Given InOrder verifier = inOrder( mockOne ); exceptionRule.expect( MockitoException.class ); exceptionRule.expectMessage( "Negative and zero values are not allowed here" ); // When verifier.verify( mockOne, calls(-1)).voidMethod(); // Then - expected exception thrown }
public void cannotInitializeForSpyAnnotation(String fieldName, Exception details) { throw new MockitoException(join("Cannot instantiate a @Spy for '" + fieldName + "' field.", "You haven't provided the instance for spying at field declaration so I tried to construct the instance.", "However, I failed because: " + details.getMessage(), "Examples of correct usage of @Spy:", " @Spy List mock = new LinkedList();", " @Spy Foo foo; //only if Foo has parameterless constructor", " //also, don't forget about MockitoAnnotations.initMocks();", ""), details); }
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()<- );" )); }