private ProduceRequestResult mockProduceRequestResult() throws InterruptedException { ProduceRequestResult mockProduceRequestResult = mock(ProduceRequestResult.class); when(mockProduceRequestResult.await(anyLong(), any(TimeUnit.class))).thenReturn(true); return mockProduceRequestResult; } }
@Test public void shouldAttachNoRequestHeadersToAccessControlAllowHeadersWhenHeaderIsNull() throws Exception { HttpServletRequest request = requestMock(); when( request.getHeaders( ACCESS_CONTROL_REQUEST_HEADERS ) ).thenReturn( null ); filter.doFilter( request, response, chain ); verify( response, never() ).addHeader( eq( ACCESS_CONTROL_ALLOW_HEADERS ), anyString() ); }
@Test public void testCloseError() throws IOException { Reader reader = mock(Reader.class); when(reader.read(any(char[].class), anyInt(), anyInt())).thenReturn(-1); doThrow(new IOException()).when(reader).close(); WsTestUtil.mockReader(wsClient, reader); exception.expect(IllegalStateException.class); metricsRepositoryLoader.load(); } }
@SuppressWarnings( "unchecked" ) void getsProcessedByStoreScanFrom( IndexStoreView mock ) { when( mock.visitNodes( any(int[].class), any( IntPredicate.class ), any( Visitor.class ), isNull(), anyBoolean() ) ).thenAnswer( this ); }
@SuppressWarnings( "unchecked" ) private static IndexStoreView newStoreView( EntityUpdates... updates ) { IndexStoreView storeView = mock( IndexStoreView.class ); when( storeView.visitNodes( any(), any(), any(), any(), anyBoolean() ) ).thenAnswer( invocation -> { Visitor<EntityUpdates,IndexPopulationFailedKernelException> visitorArg = invocation.getArgument( 2 ); return new IndexEntryUpdateScan( updates, visitorArg ); } ); return storeView; }
@SuppressWarnings("unchecked") @Test public void shouldCallOnNextAndOnCompleted() throws Exception { Callable<String> func = mock(Callable.class); when(func.call()).thenReturn("test_value"); Observable<String> fromCallableObservable = Observable.fromCallable(func); Observer<Object> observer = TestHelper.mockObserver(); fromCallableObservable.subscribe(observer); verify(observer).onNext("test_value"); verify(observer).onComplete(); verify(observer, never()).onError(any(Throwable.class)); }
private IndexPopulation addPopulator( IndexPopulator indexPopulator, int id ) throws FlipFailedKernelException { FlippableIndexProxy indexProxy = mock( FlippableIndexProxy.class ); when( indexProxy.getState() ).thenReturn( InternalIndexState.ONLINE ); doAnswer( invocation -> { Callable argument = invocation.getArgument( 0 ); return argument.call(); } ).when( indexProxy ).flip( any( Callable.class ), any( FailedIndexProxyFactory.class ) ); return addPopulator( indexPopulator, id, indexProxy, mock( FailedIndexProxyFactory.class ) ); } }
@Test public void initShouldCreateThreadPool() throws Throwable { ExecutorFactory mockExecutorFactory = mock( ExecutorFactory.class ); when( mockExecutorFactory.create( anyInt(), anyInt(), any(), anyInt(), anyBoolean(), any() ) ).thenReturn( Executors.newCachedThreadPool() ); ExecutorBoltScheduler scheduler = new ExecutorBoltScheduler( CONNECTOR_KEY, mockExecutorFactory, jobScheduler, logService, 0, 10, Duration.ofMinutes( 1 ), 0, ForkJoinPool.commonPool() ); scheduler.start(); verify( jobScheduler ).threadFactory( Group.BOLT_WORKER ); verify( mockExecutorFactory, times( 1 ) ).create( anyInt(), anyInt(), any( Duration.class ), anyInt(), anyBoolean(), any( ThreadFactory.class ) ); }
@Test public void shouldHandleExceptionDuringPluginInteraction() throws Exception { when(pluginManager.isPluginOfType(PACKAGE_MATERIAL_EXTENSION, PLUGIN_ID)).thenReturn(true); when(pluginManager.submitTo(eq(PLUGIN_ID), eq(PACKAGE_MATERIAL_EXTENSION), requestArgumentCaptor.capture())).thenThrow(new RuntimeException("exception-from-plugin")); try { extension.checkConnectionToPackage(PLUGIN_ID, packageConfiguration, repositoryConfiguration); } catch (Exception e) { assertThat(e.getMessage(), is("Interaction with plugin with id 'plugin-id' implementing 'package-repository' extension failed while requesting for 'check-package-connection'. Reason: [exception-from-plugin]")); } }
@Test public void blockWhenPollConditionNotSatisfied() { long timeout = 4000L; NetworkClient mockNetworkClient = mock(NetworkClient.class); ConsumerNetworkClient consumerClient = new ConsumerNetworkClient(new LogContext(), mockNetworkClient, metadata, time, 100, 1000, Integer.MAX_VALUE); when(mockNetworkClient.inFlightRequestCount()).thenReturn(1); consumerClient.poll(time.timer(timeout), () -> true); verify(mockNetworkClient).poll(eq(timeout), anyLong()); }
@Test(dataProvider = "schedule") public void schedule(long nanos, int expired) { when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); for (int timeout : new int[] { 25, 90, 240 }) { timerWheel.schedule(new Timer(TimeUnit.SECONDS.toNanos(timeout))); } timerWheel.advance(nanos); verify(cache, times(expired)).evictEntry(any(), any(), anyLong()); for (Node<?, ?> node : captor.getAllValues()) { assertThat(node.getVariableTime(), is(lessThan(nanos))); } }
@Test public void shouldNotStopWhenException() { setUpMocks(); when(manager.getFromQueue()).thenThrow(new RuntimeException("Unexpected exception")).thenReturn(notification).thenReturn(null); doAnswer(addUser(ASSIGNEE_SIMON, emailChannel)).when(commentOnIssueAssignedToMe).dispatch(same(notification), any(NotificationDispatcher.Context.class)); doAnswer(addUser(CREATOR_SIMON, emailChannel)).when(commentOnIssueCreatedByMe).dispatch(same(notification), any(NotificationDispatcher.Context.class)); underTest.start(); verify(emailChannel, timeout(2000)).deliver(notification, ASSIGNEE_SIMON); underTest.stop(); verify(gtalkChannel, never()).deliver(notification, ASSIGNEE_SIMON); }
@SuppressWarnings("unchecked") @Test public void shouldCallOnError() throws Exception { Callable<Object> func = mock(Callable.class); Throwable throwable = new IllegalStateException("Test exception"); when(func.call()).thenThrow(throwable); Observable<Object> fromCallableObservable = Observable.fromCallable(func); Observer<Object> observer = TestHelper.mockObserver(); fromCallableObservable.subscribe(observer); verify(observer, never()).onNext(any()); verify(observer, never()).onComplete(); verify(observer).onError(throwable); }
@Test public void checkForUpgradeShouldKillAgentIfAgentMD5doesNotMatch() { when(systemEnvironment.getAgentMd5()).thenReturn("old-agent-md5"); expectHeaderValue(SystemEnvironment.AGENT_CONTENT_MD5_HEADER, "new-agent-md5"); RuntimeException toBeThrown = new RuntimeException("Boo!"); doThrow(toBeThrown).when(jvmExitter).jvmExit(anyString(), anyString(), anyString()); try { agentUpgradeService.checkForUpgradeAndExtraProperties(); fail("should have done jvm exit"); } catch (Exception e) { assertSame(e, toBeThrown); } verify(jvmExitter).jvmExit("itself", "old-agent-md5", "new-agent-md5"); }
/** * see #testTruncateNotCalledIfSizeIsSameAsTargetSize */ @Test public void testTruncateIfSizeIsDifferentToTargetSize() throws IOException { FileChannel channelMock = mock(FileChannel.class); when(channelMock.size()).thenReturn(42L); when(channelMock.truncate(anyLong())).thenReturn(channelMock); FileRecords fileRecords = new FileRecords(tempFile(), channelMock, 0, Integer.MAX_VALUE, false); fileRecords.truncateTo(23); verify(channelMock, atLeastOnce()).size(); verify(channelMock).truncate(23); }
@Test public void testListIterable() { Observable<String> o = Observable.fromIterable(Arrays.<String> asList("one", "two", "three")); Observer<String> observer = TestHelper.mockObserver(); o.subscribe(observer); verify(observer, times(1)).onNext("one"); verify(observer, times(1)).onNext("two"); verify(observer, times(1)).onNext("three"); verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); }
@Test public void testNextTupleEmitsAtMostOneTuple() { //The spout should emit at most one message per call to nextTuple //This is necessary for Storm to be able to throttle the spout according to maxSpoutPending KafkaSpout<String, String> spout = SpoutWithMockedConsumerSetupHelper.setupSpout(spoutConfig, conf, contextMock, collectorMock, consumerMock, partition); Map<TopicPartition, List<ConsumerRecord<String, String>>> records = new HashMap<>(); records.put(partition, SpoutWithMockedConsumerSetupHelper.createRecords(partition, 0, 10)); when(consumerMock.poll(anyLong())) .thenReturn(new ConsumerRecords<>(records)); spout.nextTuple(); verify(collectorMock, times(1)).emit(anyString(), anyList(), any(KafkaSpoutMessageId.class)); }
private ExplicitIndexTransactionStateImpl newExplicitIndexTxState() { indexConfigStore = mock( IndexConfigStore.class ); when( indexConfigStore.get( eq( Node.class ), anyString() ) ).thenReturn( config ); when( indexConfigStore.get( eq( Relationship.class ), anyString() ) ).thenReturn( config ); ExplicitIndexProvider explicitIndexProvider = mock( ExplicitIndexProvider.class ); when( explicitIndexProvider.getProviderByName( anyString() ) ).thenReturn( provider ); return new ExplicitIndexTransactionStateImpl( indexConfigStore, explicitIndexProvider ); } }
@Test public void expire_reschedule() { when(cache.evictEntry(captor.capture(), any(), anyLong())).thenAnswer(invocation -> { Timer timer = (Timer) invocation.getArgument(0); timer.setVariableTime(timerWheel.nanos + 100); return false; }); timerWheel.schedule(new Timer(100)); timerWheel.advance(TimerWheel.SPANS[0]); verify(cache).evictEntry(any(), any(), anyLong()); assertThat(captor.getValue().getNextInVariableOrder(), is(not(nullValue()))); assertThat(captor.getValue().getPreviousInVariableOrder(), is(not(nullValue()))); }
@Test public void shouldPropagateReturnValueFromVisitFileFailed() throws IOException { for ( FileVisitResult result : FileVisitResult.values() ) { when( wrapped.visitFileFailed( any(), any() ) ).thenReturn( result ); assertThat( decorator.visitFileFailed( null, null ), is( result ) ); } }