private static ExecutionGraphManipulator getMockedGraph(int address, HeapItem value) { ExecutionGraphManipulator manipulator = mock(ExecutionGraphManipulator.class); BuilderInstruction instruction = mock(BuilderInstruction.class, withSettings().extraInterfaces(OneRegisterInstruction.class)); when(((OneRegisterInstruction) instruction).getRegisterA()).thenReturn(REGISTER); when(manipulator.getRegisterConsensus(address, REGISTER)).thenReturn(value); when(manipulator.getInstruction(address)).thenReturn(instruction); return manipulator; }
private static Object spyInstance(Field field, Object instance) { return Mockito.mock(instance.getClass(), withSettings().spiedInstance(instance) .defaultAnswer(CALLS_REAL_METHODS) .name(field.getName())); }
public static Object processAnnotationForMock(Mock annotation, Class<?> type, String name) { MockSettings mockSettings = Mockito.withSettings(); if (annotation.extraInterfaces().length > 0) { // never null mockSettings.extraInterfaces(annotation.extraInterfaces()); } if ("".equals(annotation.name())) { mockSettings.name(name); } else { mockSettings.name(annotation.name()); } if(annotation.serializable()){ mockSettings.serializable(); } if(annotation.stubOnly()){ mockSettings.stubOnly(); } if(annotation.lenient()){ mockSettings.lenient(); } // see @Mock answer default value mockSettings.defaultAnswer(annotation.answer()); return Mockito.mock(type, mockSettings); } }
private MockSettings withSettingsUsing(GenericMetadataSupport returnTypeGenericMetadata, MockCreationSettings parentMockSettings) { MockSettings mockSettings = returnTypeGenericMetadata.hasRawExtraInterfaces() ? withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces()) : withSettings(); return propagateSerializationSettings(mockSettings, parentMockSettings) .defaultAnswer(returnsDeepStubsAnswerUsing(returnTypeGenericMetadata)); }
protected void blockDataContainerIteration(final Cache<?, ?> cache, final CyclicBarrier barrier) { InternalDataContainer dataContainer = TestingUtil.extractComponent(cache, InternalDataContainer.class); final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(dataContainer); InternalDataContainer mockContainer = mock(InternalDataContainer.class, withSettings().defaultAnswer(forwardedAnswer)); doAnswer(invocation -> { // Wait for main thread to sync up barrier.await(10, TimeUnit.SECONDS); // Now wait until main thread lets us through barrier.await(10, TimeUnit.SECONDS); return forwardedAnswer.answer(invocation); }).when(mockContainer).removeSegments(any()); TestingUtil.replaceComponent(cache, InternalDataContainer.class, mockContainer, true); } }
private void testFilterConverterUnusedDuringIteration(final StateListener<String, String> listener) { final List<CacheEntry<String, String>> initialValues = new ArrayList<CacheEntry<String, String>>(10); for (int i = 0; i < 10; i++) { String key = "key-" + i; String value = "value-" + i; initialValues.add(new ImmortalCacheEntry(key, value)); } // Note we don't actually use the filter/converter to retrieve values since it is being mocked, thus we can assert // the filter/converter are not used by us CacheStream mockStream = mockStream(); doReturn(initialValues.iterator()).when(mockStream).iterator(); when(mockCache.withEncoding(any(Class.class), any(Class.class)).cacheEntrySet().stream()).thenReturn(mockStream); CacheEventFilter filter = mock(CacheEventFilter.class, withSettings().serializable()); CacheEventConverter converter = mock(CacheEventConverter.class, withSettings().serializable()); n.addListener(listener, filter, converter); verifyEvents(isClustered(listener), listener, initialValues); verify(filter, never()).accept(any(), any(), any(Metadata.class), any(), any(Metadata.class), any(EventType.class)); verify(converter, never()).convert(any(), any(), any(Metadata.class), any(), any(Metadata.class), any(EventType.class)); }
@Test public void configFailsOnInitialize() throws Exception { final Lifecycle connProvider = mock(Lifecycle.class, withSettings().extraInterfaces(ConnectionProvider.class)); final String expectedExceptionMessage = "Init failed!"; doThrow(new RuntimeException(expectedExceptionMessage)).when(connProvider).initialise(); when(connectionProviderResolver.resolve(any())).thenReturn(new Pair<>(connProvider, mock(ResolverSetResult.class))); expected.expectCause(hasMessage(is(InitialisationException.class.getName() + ": " + expectedExceptionMessage))); try { provider.get(event); } finally { verify(connProvider).initialise(); verify(connProvider, never()).start(); verify(connProvider, never()).stop(); verify(connProvider).dispose(); } }
public static MuleContextWithRegistry mockMuleContext() { final MuleContextWithRegistry muleContext = mock(DefaultMuleContext.class, withSettings().defaultAnswer(RETURNS_DEEP_STUBS).extraInterfaces(PrivilegedMuleContext.class).lenient()); when(muleContext.getUniqueIdString()).thenReturn(UUID.getUUID()); when(muleContext.getDefaultErrorHandler(empty())).thenReturn(new OnErrorPropagateHandler()); StreamingManager streamingManager = mock(StreamingManager.class, RETURNS_DEEP_STUBS); try { MuleRegistry registry = mock(MuleRegistry.class, withSettings().lenient()); when(muleContext.getRegistry()).thenReturn(registry); ComponentInitialStateManager componentInitialStateManager = mock(ComponentInitialStateManager.class, withSettings().lenient()); when(componentInitialStateManager.mustStartMessageSource(any())).thenReturn(true); when(registry.lookupObject(ComponentInitialStateManager.SERVICE_ID)).thenReturn(componentInitialStateManager); doReturn(streamingManager).when(registry).lookupObject(StreamingManager.class); doReturn(mock(NotificationDispatcher.class)).when(registry).lookupObject(NotificationDispatcher.class); doReturn(mock(ObjectStoreManager.class, RETURNS_DEEP_STUBS)).when(registry).lookupObject(OBJECT_STORE_MANAGER); } catch (RegistrationException e) { throw new RuntimeException(e); } return muleContext; }
private static JobEntryInterface createJobEntry( String directory ) { JobEntryInterface jobEntryInterface = mock( JobEntryInterface.class, withSettings().extraInterfaces( HasRepositoryDirectories.class ) ); when( jobEntryInterface.isReferencedObjectEnabled() ).thenReturn( new boolean[] { true } ); doAnswer( invocationOnMock -> new ObjectLocationSpecificationMethod[] { ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME } ) .when( ( (HasRepositoryDirectories) jobEntryInterface ) ).getSpecificationMethods(); doAnswer( invocationOnMock -> new String[] { directory } ) .when( (HasRepositoryDirectories) jobEntryInterface ).getDirectories(); return jobEntryInterface; }
@Before public void before() throws Exception { mCommandManager = new CommandManager(); // Create mock job info. mJobconfig = Mockito.mock(JobConfig.class, Mockito.withSettings().serializable()); Mockito.when(mJobconfig.getName()).thenReturn("mock"); mJobId = 1; // Create mock job definition. @SuppressWarnings("unchecked") JobDefinition<JobConfig, Serializable, Serializable> mockJobDefinition = Mockito.mock(JobDefinition.class); JobDefinitionRegistry singleton = PowerMockito.mock(JobDefinitionRegistry.class); Whitebox.setInternalState(JobDefinitionRegistry.class, "INSTANCE", singleton); Mockito.when(singleton.getJobDefinition(mJobconfig)).thenReturn(mockJobDefinition); mJobDefinition = mockJobDefinition; // Create test worker. mWorkerInfo = new WorkerInfo(); mWorkerInfo.setId(0); mWorkerInfoList = Lists.newArrayList(mWorkerInfo); mUfsManager = Mockito.mock(UfsManager.class); }
@Test public void testFailStartingMessageSourceOnLifecycleShouldStopStartedPipelineProcesses() throws Exception { // Need to start mule context to have endpoints started during flow start muleContext.start(); MessageSource mockMessageSource = mock(MessageSource.class, withSettings().extraInterfaces(Startable.class, Stoppable.class)); doThrow(new LifecycleException(mock(I18nMessage.class), mockMessageSource)).when(((Startable) mockMessageSource)) .start(); final List<Processor> processors = new ArrayList<>(flow.getProcessors()); Processor mockMessageProcessor = spy(new LifecycleTrackerProcessor()); processors.add(mockMessageProcessor); after(); flow = (DefaultFlow) Flow.builder(FLOW_NAME, muleContext) .source(mockMessageSource) .processors(processors).build(); flow.initialise(); try { flow.start(); fail(); } catch (LifecycleException e) { } verify((Startable) mockMessageProcessor, times(1)).start(); verify((Stoppable) mockMessageProcessor, times(1)).stop(); verify((Startable) mockMessageSource, times(1)).start(); verify((Stoppable) mockMessageSource, times(1)).stop(); }
@Test public void testOnMessageEOF() throws IOException { InputStream mis = mock(InputStream.class, withSettings().extraInterfaces(Seekable.class, PositionedReadable.class)); doReturn(-1).when(mis).read(any(byte[].class), anyInt(), anyInt()); FSDataInputStream fdis = new FSDataInputStream(mis); Response response = getResponse(7L, 4096, fdis); InOrder inOrder = Mockito.inOrder(mis); inOrder.verify((Seekable) mis).seek(7); inOrder.verify(mis).read(any(byte[].class), anyInt(), anyInt()); assertEquals(-1, ((DFS.GetFileDataResponse) response.pBody).getRead()); assertEquals(0, response.dBodies.length); }
protected AsyncInterceptorChain mockEntrySet(final Cache<?, ?> cache, StreamMocking mocking) { AsyncInterceptorChain chain = TestingUtil.extractComponent(cache, AsyncInterceptorChain.class); AsyncInterceptorChain mockChain = spy(chain); doAnswer(i -> { CacheSet cacheSet = (CacheSet) i.callRealMethod(); CacheSet mockSet = mock(CacheSet.class, withSettings().defaultAnswer(delegatesTo(cacheSet))); when(mockSet.stream()).then(j -> { CacheStream stream = cacheSet.stream(); return mockStream(stream, mocking); }); return mockSet; }).when(mockChain).invoke(any(InvocationContext.class), any(EntrySetCommand.class)); TestingUtil.replaceComponent(cache, AsyncInterceptorChain.class, mockChain, true); return chain; } }
@Test @Ignore("MULE-16210") public void originalExceptionThrownWhenStartAndStopOfSourceBothFail() throws Exception { final Exception startException = new IllegalArgumentException(); final Exception stopException = new IllegalStateException(); MessageSource source = mock(MessageSource.class, withSettings().extraInterfaces(Startable.class, Stoppable.class)); doThrow(startException).when((Startable) source).start(); doThrow(stopException).when((Stoppable) source).stop(); muleContext = spy(muleContext); flow = (DefaultFlow) Flow.builder(FLOW_NAME, muleContext) .source(source) .processors(singletonList(mock(Processor.class))) .build(); flow.initialise(); muleContext.start(); try { flow.start(); fail("was expecting failure"); } catch (LifecycleException e) { assertThat(e.getCause(), instanceOf(MuleException.class)); assertThat(e.getCause().getCause(), sameInstance(startException)); } } }
@Before public void before() { parseResult = mock(GfshParseResult.class); result = new ResultModel(); executor = spy(CommandExecutor.class); testCommand = mock(SingleGfshCommand.class, withSettings().extraInterfaces(UpdateAllConfigurationGroupsMarker.class)); ccService = spy(InternalConfigurationPersistenceService.class); configRegion = mock(AbstractRegion.class); doReturn(ccService).when(testCommand).getConfigurationPersistenceService(); doCallRealMethod().when(ccService).updateCacheConfig(any(), any()); doReturn(true).when(ccService).lockSharedConfiguration(); doNothing().when(ccService).unlockSharedConfiguration(); doReturn(configRegion).when(ccService).getConfigurationRegion(); }
protected void waitUntilNotificationRaised(final Cache<?, ?> cache, final CheckPoint checkPoint) { CacheNotifier cn = TestingUtil.extractComponent(cache, CacheNotifier.class); final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(cn); CacheNotifier mockNotifier = mock(CacheNotifier.class, withSettings().extraInterfaces(ClusterCacheNotifier.class) .defaultAnswer(forwardedAnswer)); Answer answer = invocation -> { // Wait for main thread to sync up checkPoint.trigger("pre_raise_notification_invoked"); // Now wait until main thread lets us through checkPoint.awaitStrict("pre_raise_notification_release", 10, TimeUnit.SECONDS); try { return forwardedAnswer.answer(invocation); } finally { // Wait for main thread to sync up checkPoint.trigger("post_raise_notification_invoked"); // Now wait until main thread lets us through checkPoint.awaitStrict("post_raise_notification_release", 10, TimeUnit.SECONDS); } }; doAnswer(answer).when(mockNotifier).notifyCacheEntryCreated(any(), any(), any(Metadata.class), eq(false), any(InvocationContext.class), any(FlagAffectedCommand.class)); doAnswer(answer).when(mockNotifier).notifyCacheEntryModified(any(), any(), any(Metadata.class), any(), any(Metadata.class), anyBoolean(), any(InvocationContext.class), any(FlagAffectedCommand.class)); doAnswer(answer).when(mockNotifier).notifyCacheEntryRemoved(any(), any(), any(Metadata.class), eq(false), any(InvocationContext.class), any(FlagAffectedCommand.class)); TestingUtil.replaceComponent(cache, CacheNotifier.class, mockNotifier, true); }
private TableWriteFunction createMockTableWriteFunction() { return mock(TableWriteFunction.class, withSettings().serializable()); }
/** * Creates mock object of given class or interface. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface to mock * @return mock object */ public static <T> T mock(Class<T> classToMock) { return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS)); }
@Test public void testStreamApplicationWithTableAndSideInput() { mockStreamAppDesc = new StreamApplicationDescriptorImpl(getRepartitionJoinStreamApplication(), mockConfig); // add table to the RepartitionJoinStreamApplication GenericInputDescriptor<KV<String, Object>> sideInput1 = inputSystemDescriptor.getInputDescriptor("sideInput1", defaultSerde); BaseTableDescriptor mockTableDescriptor = new MockLocalTableDescriptor("testTable", defaultSerde) .withSideInputs(Arrays.asList(sideInput1.getStreamId())) .withSideInputsProcessor(mock(SideInputsProcessor.class, withSettings().serializable())) .withConfig("mock.table.provider.config", "mock.config.value"); // add side input and terminate at table in the appplication mockStreamAppDesc.getInputStream(sideInput1).sendTo(mockStreamAppDesc.getTable(mockTableDescriptor)); StreamEdge sideInputEdge = new StreamEdge(new StreamSpec(sideInput1.getStreamId(), "sideInput1", inputSystemDescriptor.getSystemName()), false, false, mockConfig); // need to put the sideInput related stream configuration to the original config // TODO: this is confusing since part of the system and stream related configuration is generated outside the JobGraphConfigureGenerator // It would be nice if all system and stream related configuration is generated in one place and only intermediate stream // configuration is generated by JobGraphConfigureGenerator Map<String, String> configs = new HashMap<>(mockConfig); configs.putAll(sideInputEdge.generateConfig()); mockConfig = spy(new MapConfig(configs)); configureJobNode(mockStreamAppDesc); // create the JobGraphConfigureGenerator and generate the jobConfig for the jobNode JobNodeConfigurationGenerator configureGenerator = new JobNodeConfigurationGenerator(); JobConfig jobConfig = configureGenerator.generateJobConfig(mockJobNode, "testJobGraphJson"); Config expectedJobConfig = getExpectedJobConfig(mockConfig, mockJobNode.getInEdges()); validateJobConfig(expectedJobConfig, jobConfig); Map<String, Serde> deserializedSerdes = validateAndGetDeserializedSerdes(jobConfig, 5); validateTableConfigure(jobConfig, deserializedSerdes, mockTableDescriptor); }
@Test public void proxyingWorksIfInfoReturnsNullEntityManagerInterface() { EntityManagerFactory emf = mock(EntityManagerFactory.class, withSettings().extraInterfaces(EntityManagerFactoryInfo.class)); // EntityManagerFactoryInfo.getEntityManagerInterface returns null assertThat(SharedEntityManagerCreator.createSharedEntityManager(emf), is(notNullValue())); }