public void testMyFunction() throws Exception { Application mock = mock(Application.class); when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return (String) args[0]; } }); assertEquals("someString",mock.myFunction("someString")); assertEquals("anotherString",mock.myFunction("anotherString")); }
private Function<IndexSlot,String> slotToStringFunction() { Function<IndexSlot,String> factory = mock( Function.class ); when( factory.apply( any( IndexSlot.class ) ) ).then( invocationOnMock -> String.valueOf( (IndexSlot) invocationOnMock.getArgument( 0 ) ) ); return factory; } }
@Override public Iterable<FileStatus> answer(InvocationOnMock invocation) throws Throwable { counter[0]++; LOG.debug(counter[0] + "/ " + expected + ") Wrapping call to getDeletableFiles for files: " + invocation.getArgument(0)); @SuppressWarnings("unchecked") Iterable<FileStatus> ret = (Iterable<FileStatus>) invocation.callRealMethod(); if (counter[0] >= expected) finished.countDown(); return ret; } }).when(delegateSpy).getDeletableFiles(Mockito.anyListOf(FileStatus.class));
private boolean wantedArgumentPositionIsValidForInvocation(InvocationOnMock invocation, int argumentPosition) { if (argumentPosition < 0) { return false; } if (!invocation.getMethod().isVarArgs()) { return invocation.getArguments().length > argumentPosition; } // for all varargs accepts positive ranges return true; }
public Object answer(InvocationOnMock invocation) throws Throwable { if (Modifier.isAbstract(invocation.getMethod().getModifiers())) { return RETURNS_DEFAULTS.answer(invocation); } return invocation.callRealMethod(); }
private static ExecutorService sameThreadExecutor() throws InterruptedException { ExecutorService executor = immediateExecutor(); when( executor.awaitTermination( anyLong(), any() ) ).thenReturn( true ); doAnswer( invocation -> { ((Runnable) invocation.getArgument( 0 )).run(); return null; } ).when( executor ).execute( any() ); return executor; }
@Before public void before() throws Exception { when(webSocketClient.connectBlocking()).thenReturn(true); doAnswer(invocation -> { listener = invocation.getArgumentAt(0, WebSocketListener.class); return null; }).when(webSocketClient).setListener(any()); doAnswer(invocation -> { String message = invocation.getArgumentAt(0, String.class); int requestId = getRequestId(message); sendSubscriptionConfirmation(requestId); return null; }).when(webSocketClient).send(anyString()); webSocketService.connect(); }
@Before public void setUp() { cache = mock(InternalCacheForClientAccess.class); doReturn(cache).when(cache).getCacheForProcessingClientRequests(); region = mock(Region.class); when(cache.getRegion(REGION)).thenReturn(region); security = mock(Security.class); doThrow(NotAuthorizedException.class).when(security).authorize(any()); doThrow(NotAuthorizedException.class).when(security).authorize(any(), any(), any(), any()); when(security.postProcess(any(), any(), any())).then(invocation -> invocation.getArgument(2)); when(security.needsPostProcessing()).thenReturn(true); authorizingCache = new SecureCacheImpl(cache, security); }
/** * Set up gRPC interface mocks. */ @Before public void before() { mClient = mock(BlockWorkerClient.class); mRequestObserver = mock(ClientCallStreamObserver.class); when(mClient.writeBlock(any(StreamObserver.class))).thenAnswer((args) -> { mResponseObserver = args.getArgumentAt(0, ClientResponseObserver.class); return mRequestObserver; }); when(mRequestObserver.isReady()).thenReturn(true); mStream = new GrpcBlockingStream<>(mClient::writeBlock, BUFFER_SIZE, TEST_MESSAGE); }
@Before public void setUp() throws Exception { configuration = mock(ConfigurationRegistry.class); TracingPlugin tracingPlugin = mock(TracingPlugin.class); when(tracingPlugin.getRequestMonitor()).thenReturn(mock(RequestMonitor.class)); when(tracingPlugin.getProfilerRateLimitPerMinuteOption()).thenReturn(mock(ConfigurationOption.class)); when(tracingPlugin.isSampled(any())).thenReturn(true); when(configuration.getConfig(TracingPlugin.class)).thenReturn(tracingPlugin); servletPlugin = mock(ServletPlugin.class); when(servletPlugin.isWidgetAndStagemonitorEndpointsAllowed(any(HttpServletRequest.class))).thenReturn(Boolean.TRUE); when(configuration.getConfig(ServletPlugin.class)).thenReturn(servletPlugin); final CorePlugin corePlugin = mock(CorePlugin.class); when(corePlugin.getThreadPoolQueueCapacityLimit()).thenReturn(1000); when(configuration.getConfig(CorePlugin.class)).thenReturn(corePlugin); WidgetAjaxSpanReporter reporter = new WidgetAjaxSpanReporter(); spanServlet = new SpanServlet(configuration, reporter, 1500); spanServlet.init(); connectionId = UUID.randomUUID().toString(); final SamplePriorityDeterminingSpanEventListener samplePriorityDeterminingSpanInterceptor = mock(SamplePriorityDeterminingSpanEventListener.class); when(samplePriorityDeterminingSpanInterceptor.onSetTag(anyString(), anyString())).then(invocation -> invocation.getArgument(1)); when(samplePriorityDeterminingSpanInterceptor.onSetTag(anyString(), anyBoolean())).then(invocation -> invocation.getArgument(1)); when(samplePriorityDeterminingSpanInterceptor.onSetTag(anyString(), any(Number.class))).then(invocation -> invocation.getArgument(1)); final ReportingSpanEventListener reportingSpanEventListener = new ReportingSpanEventListener(configuration); reportingSpanEventListener.addReporter(reporter); Tracer tracer = TracingPlugin.createSpanWrappingTracer(new MockTracer(new ThreadLocalScopeManager(), new B3Propagator()), configuration, new Metric2Registry(), ServiceLoader.load(SpanEventListenerFactory.class), samplePriorityDeterminingSpanInterceptor, reportingSpanEventListener); GlobalTracerTestHelper.override(tracer); when(tracingPlugin.getTracer()).thenReturn(tracer); }
@Before public void setup() { EmbeddedProxySPI manager = mock( EmbeddedProxySPI.class ); when( manager.newNodeProxy( anyLong() ) ).thenAnswer( invocationOnMock -> { long id = invocationOnMock.getArgument( 0 ); NodeProxy mock = mock( NodeProxy.class ); when( mock.getId() ).thenReturn( id ); return mock; } ); when( manager.newRelationshipProxy( anyLong() ) ).thenAnswer( invocationOnMock -> { long id = invocationOnMock.getArgument( 0 ); RelationshipProxy mock = mock( RelationshipProxy.class ); when( mock.getId() ).thenReturn( id ); return mock; } ); converter = new ParameterConverter( manager ); }
final OneShotLatch completeSubtask = new OneShotLatch(); Environment mockEnvironment = spy(new MockEnvironmentBuilder().build()); thenAnswer((Answer<OperatorSnapshotFinalizer>) invocation -> { createSubtask.trigger(); completeSubtask.await(); Object[] arguments = invocation.getArguments(); return new OperatorSnapshotFinalizer((OperatorSnapshotFutures) arguments[0]); CheckpointMetaData checkpointMetaData = new CheckpointMetaData(checkpointId, timestamp); final StreamOperator<?> streamOperator = mock(StreamOperator.class); final OperatorID operatorID = new OperatorID(); when(streamOperator.getOperatorID()).thenReturn(operatorID); KeyedStateHandle managedKeyedStateHandle = mock(KeyedStateHandle.class); DoneFuture.of(SnapshotResult.of(rawOperatorStateHandle))); when(streamOperator.snapshotState(anyLong(), anyLong(), any(CheckpointOptions.class), any(CheckpointStreamFactory.class))).thenReturn(operatorSnapshotResult);
throw new NoSuchMethodError(); }); TaskClient client = Mockito.mock(TaskClient.class); WorkflowTaskCoordinator coordinator = new WorkflowTaskCoordinator.Builder() .withWorkers(worker) .withWorkerNamePrefix("test-worker-") .build(); when(client.batchPollTasksInDomain(anyString(), anyString(), anyString(), anyInt(), anyInt())).thenReturn(ImmutableList.of(new Task())); when(client.ack(anyString(), anyString())).thenReturn(true); CountDownLatch latch = new CountDownLatch(1); doAnswer(invocation -> { assertEquals("test-worker-0", Thread.currentThread().getName()); Object[] args = invocation.getArguments(); TaskResult result = (TaskResult) args[0]; assertEquals(TaskResult.Status.FAILED, result.getStatus()); return null; ).when(client).updateTask(any(), anyString()); coordinator.init(); Uninterruptibles.awaitUninterruptibly(latch);
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 ) ); } }
@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; }
@Before public void setUp() { when( populator.sampleResult() ).thenReturn( new IndexSample() ); when( storeView.indexSample( anyLong(), any( DoubleLongRegister.class ) ) ) .thenAnswer( invocation -> invocation.getArgument( 1 ) ); }
NMClient nodeManagerClient = mock(NMClient.class); Container mockContainer = mock(Container.class); when(mockContainer.getId()).thenReturn( ContainerId.newInstance( ApplicationAttemptId.newInstance( 1), i)); when(mockContainer.getNodeId()).thenReturn(NodeId.newInstance("container", 1234)); containerList.add(mockContainer); doAnswer( (InvocationOnMock invocation) -> { Container container = (Container) invocation.getArguments()[0]; resourceManagerFuture.thenCombine(leaderGatewayFuture, (resourceManagerGateway, leaderGateway) -> { return null; }) .when(nodeManagerClient) .startContainer( Matchers.any(Container.class), Matchers.any(ContainerLaunchContext.class));
@Before public void setup() throws PropertyKeyIdNotFoundKernelException { when( transaction.tokenRead() ).thenReturn( tokenRead ); when( bridge.get() ).thenReturn( stmt ); when( tokenRead.propertyKeyName( anyInt() ) ).thenAnswer( invocationOnMock -> { int id = invocationOnMock.getArgument( 0 ); return ops.propertyKeyTokenHolder().getTokenById( id ).name(); } ); }
@Before public void setUp() { HtmlSourceDecorator htmlSourceDecorator = mock(HtmlSourceDecorator.class); when(htmlSourceDecorator.getDecoratedSourceAsHtml(anyString(), anyString(), anyString())).then((Answer<String>) invocationOnMock -> "<p>" + invocationOnMock.getArguments()[0] + "</p>"); SourceService sourceService = new SourceService(db.getDbClient(), htmlSourceDecorator); wsTester = new WsTester(new SourcesWs( new LinesAction(TestComponentFinder.from(db), db.getDbClient(), sourceService, htmlSourceDecorator, userSession))); organization = db.organizations().insert(); privateProject = ComponentTesting.newPrivateProjectDto(organization); }