private <Resource> List<Integer> getTargetsSizes( RequestBuilder<Resource> requestBuilder, VerificationMode mode) { ArgumentCaptor<Integer> integerArgumentCaptor = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<Target<Resource>> targetArgumentCaptor = cast(ArgumentCaptor.forClass(Target.class)); SizeReadyCallback cb = mock(SizeReadyCallback.class); verify(requestBuilder, mode).into(targetArgumentCaptor.capture()); for (Target<Resource> target : targetArgumentCaptor.getAllValues()) { target.getSize(cb); } verify(cb, mode).onSizeReady(integerArgumentCaptor.capture(), integerArgumentCaptor.capture()); return integerArgumentCaptor.getAllValues(); }
private ArgumentCaptor<HttpHeaders> setupInfoRequest(boolean webSocketEnabled) { ArgumentCaptor<HttpHeaders> headersCaptor = ArgumentCaptor.forClass(HttpHeaders.class); when(this.infoReceiver.executeInfoRequest(any(), headersCaptor.capture())).thenReturn( "{\"entropy\":123," + "\"origins\":[\"*:*\"]," + "\"cookie_needed\":true," + "\"websocket\":" + webSocketEnabled + "}"); return headersCaptor; }
@Test public void delete() { when(request.getCookies()).thenReturn(new Cookie[] {new Cookie(AUTHENTICATION_COOKIE_NAME, "{\"return_to\":\"/settings\"}")}); underTest.delete(request, response); verify(response).addCookie(cookieArgumentCaptor.capture()); Cookie updatedCookie = cookieArgumentCaptor.getValue(); assertThat(updatedCookie.getName()).isEqualTo(AUTHENTICATION_COOKIE_NAME); assertThat(updatedCookie.getValue()).isNull(); assertThat(updatedCookie.getPath()).isEqualTo("/"); assertThat(updatedCookie.getMaxAge()).isEqualTo(0); } }
@Test public void intoImageViewWithFitAndDimensionsQueuesImageViewRequest() { ImageView target = mockFitImageViewTarget(true); when(target.getWidth()).thenReturn(100); when(target.getHeight()).thenReturn(100); new RequestCreator(picasso, URI_1, 0).fit().into(target); verify(picasso).enqueueAndSubmit(actionCaptor.capture()); assertThat(actionCaptor.getValue()).isInstanceOf(ImageViewAction.class); }
@Test public void execute_validAeqId_OK() throws Throwable { XmlEntity xmlEntity = mock(XmlEntity.class); doReturn(xmlEntity).when(function).getAEQXmlEntity(anyString(), anyString()); when(cache.getAsyncEventQueue(TEST_AEQ_ID)).thenReturn(mockAEQ); function.execute(mockContext); verify(resultSender).lastResult(resultCaptor.capture()); CliFunctionResult result = resultCaptor.getValue(); assertThat(result.isSuccessful()).isTrue(); assertThat(result.getXmlEntity()).isNotNull(); assertThat(result.getThrowable()).isNull(); }
@Test @SuppressWarnings({"rawtypes", "unchecked"}) public void cancelInactivityTasks() throws Exception { TcpConnection<byte[]> tcpConnection = getTcpConnection(); ScheduledFuture future = mock(ScheduledFuture.class); when(this.taskScheduler.scheduleWithFixedDelay(any(), eq(1L))).thenReturn(future); tcpConnection.onReadInactivity(mock(Runnable.class), 2L); tcpConnection.onWriteInactivity(mock(Runnable.class), 2L); this.webSocketHandlerCaptor.getValue().afterConnectionClosed(this.webSocketSession, CloseStatus.NORMAL); verify(future, times(2)).cancel(true); verifyNoMoreInteractions(future); }
@Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void receiptNotReceived() { TaskScheduler taskScheduler = mock(TaskScheduler.class); this.session.afterConnected(this.connection); this.session.setTaskScheduler(taskScheduler); AtomicReference<Boolean> notReceived = new AtomicReference<>(); ScheduledFuture future = mock(ScheduledFuture.class); when(taskScheduler.schedule(any(Runnable.class), any(Date.class))).thenReturn(future); StompHeaders headers = new StompHeaders(); headers.setDestination("/topic/foo"); headers.setReceipt("my-receipt"); Receiptable receiptable = this.session.send(headers, "payload"); receiptable.addReceiptLostTask(() -> notReceived.set(true)); ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class); verify(taskScheduler).schedule(taskCaptor.capture(), (Date) notNull()); Runnable scheduledTask = taskCaptor.getValue(); assertNotNull(scheduledTask); assertNull(notReceived.get()); scheduledTask.run(); assertTrue(notReceived.get()); verify(future).cancel(true); verifyNoMoreInteractions(future); }
@Test public void oldSecurityShouldFailIfNotAuthorized() throws Exception { when(this.securityService.isClientSecurityRequired()).thenReturn(true); when(this.securityService.isIntegratedSecurity()).thenReturn(false); doThrow(new NotAuthorizedException("")).when(this.authzRequest) .registerInterestAuthorize(eq(REGION_NAME), eq(KEY), anyInt(), any()); this.registerInterest.cmdExecute(this.message, this.serverConnection, this.securityService, 0); verify(this.authzRequest).registerInterestAuthorize(eq(REGION_NAME), eq(KEY), anyInt(), any()); ArgumentCaptor<NotAuthorizedException> argument = ArgumentCaptor.forClass(NotAuthorizedException.class); verify(this.chunkedResponseMessage).addObjPart(argument.capture()); assertThat(argument.getValue()).isExactlyInstanceOf(NotAuthorizedException.class); verify(this.chunkedResponseMessage).sendChunk(this.serverConnection); }
@Test public void processWithNullPointerExceptionFromOperationOnRegionWithNoSystemFailureSendsReplyWithNPE() throws Exception { when(msg.operateOnRegion(dm, r, startTime)).thenThrow(NullPointerException.class); doNothing().when(msg).checkForSystemFailure(); msg.setSender(sender); msg.process(dm); verify(dm, times(1)).putOutgoing(any()); ArgumentCaptor<ReplyException> captor = ArgumentCaptor.forClass(ReplyException.class); verify(msg, times(1)).sendReply(any(), anyInt(), eq(dm), captor.capture(), eq(r), eq(startTime)); assertThat(captor.getValue().getCause()).isInstanceOf(NullPointerException.class); }
@Test public void preDrawSubmitsRequestAndCleansUp() { Picasso picasso = mock(Picasso.class); when(picasso.transformRequest(any(Request.class))).thenAnswer(TRANSFORM_REQUEST_ANSWER); RequestCreator creator = new RequestCreator(picasso, URI_1, 0); ImageView target = mockFitImageViewTarget(true); when(target.getWidth()).thenReturn(100); when(target.getHeight()).thenReturn(100); ViewTreeObserver observer = target.getViewTreeObserver(); DeferredRequestCreator request = new DeferredRequestCreator(creator, target, null); request.onPreDraw(); verify(observer).removeOnPreDrawListener(request); verify(picasso).enqueueAndSubmit(actionCaptor.capture()); Action value = actionCaptor.getValue(); assertThat(value).isInstanceOf(ImageViewAction.class); assertThat(value.request.targetWidth).isEqualTo(100); assertThat(value.request.targetHeight).isEqualTo(100); } }
@Test public void shouldConsume() { TokenChannel channel = new TokenChannel("ABC"); TokenQueue output = mock(TokenQueue.class); CodeReader codeReader = new CodeReader("ABCD"); assertThat(channel.consume(codeReader, output), is(true)); ArgumentCaptor<Token> token = ArgumentCaptor.forClass(Token.class); verify(output).add(token.capture()); assertThat(token.getValue(), is(new Token("ABC", 1, 0))); verifyNoMoreInteractions(output); assertThat(codeReader.getLinePosition(), is(1)); assertThat(codeReader.getColumnPosition(), is(3)); }
@Before public void setUpPluginRegistry() throws Exception { // Intercept access to registry registry = LifecycleSupport.registry = KettleLifecycleSupport.registry = mock( PluginRegistry.class ); registeredPlugins = new ArrayList<PluginInterface>(); when( registry.getPlugins( KettleLifecyclePluginType.class ) ).thenReturn( registeredPlugins ); typeListenerRegistration = ArgumentCaptor.forClass( PluginTypeListener.class ); doNothing().when( registry ).addPluginListener( eq( KettleLifecyclePluginType.class ), typeListenerRegistration.capture() ); }
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); WebSocketClient webSocketClient = mock(WebSocketClient.class); this.stompClient = new TestWebSocketStompClient(webSocketClient); this.stompClient.setTaskScheduler(this.taskScheduler); this.stompClient.setStompSession(this.stompSession); this.webSocketHandlerCaptor = ArgumentCaptor.forClass(WebSocketHandler.class); this.handshakeFuture = new SettableListenableFuture<>(); when(webSocketClient.doHandshake(this.webSocketHandlerCaptor.capture(), any(), any(URI.class))) .thenReturn(this.handshakeFuture); }
@Test public void broadcastRegistry() throws Exception { TestSimpUser simpUser1 = new TestSimpUser("joe"); TestSimpUser simpUser2 = new TestSimpUser("jane"); simpUser1.addSessions(new TestSimpSession("123")); simpUser1.addSessions(new TestSimpSession("456")); HashSet<SimpUser> simpUsers = new HashSet<>(Arrays.asList(simpUser1, simpUser2)); when(this.localRegistry.getUsers()).thenReturn(simpUsers); getUserRegistryTask().run(); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); verify(this.brokerChannel).send(captor.capture()); Message<?> message = captor.getValue(); assertNotNull(message); MessageHeaders headers = message.getHeaders(); assertEquals("/topic/simp-user-registry", SimpMessageHeaderAccessor.getDestination(headers)); MultiServerUserRegistry remoteRegistry = new MultiServerUserRegistry(mock(SimpUserRegistry.class)); remoteRegistry.addRemoteRegistryDto(message, this.converter, 20000); assertEquals(2, remoteRegistry.getUserCount()); assertNotNull(remoteRegistry.getUser("joe")); assertNotNull(remoteRegistry.getUser("jane")); }
@Test public void install_provides_new_Configuration_when_getBootConfiguration_is_called_and_there_is_none_in_container() { CoreExtension coreExtension1 = newCoreExtension(); CoreExtension coreExtension2 = newCoreExtension(); when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(Stream.of(coreExtension1, coreExtension2)); ComponentContainer container = new ComponentContainer(); underTest.install(container, noExtensionFilter(), noAdditionalSideFilter()); verify(coreExtension1).load(contextCaptor.capture()); verify(coreExtension2).load(contextCaptor.capture()); // verify each core extension gets its own configuration assertThat(contextCaptor.getAllValues()) .hasSameElementsAs(ImmutableSet.copyOf(contextCaptor.getAllValues())); }
private void doTestModeCannotReplayTuples(KafkaSpoutConfig<String, String> spoutConfig) { KafkaSpout<String, String> spout = SpoutWithMockedConsumerSetupHelper.setupSpout(spoutConfig, conf, contextMock, collectorMock, consumerMock, partition); when(consumerMock.poll(anyLong())).thenReturn(new ConsumerRecords<>(Collections.singletonMap(partition, SpoutWithMockedConsumerSetupHelper.createRecords(partition, 0, 1)))); spout.nextTuple(); ArgumentCaptor<KafkaSpoutMessageId> msgIdCaptor = ArgumentCaptor.forClass(KafkaSpoutMessageId.class); verify(collectorMock).emit(eq(SingleTopicKafkaSpoutConfiguration.STREAM), anyList(), msgIdCaptor.capture()); assertThat("Should have captured a message id", msgIdCaptor.getValue(), not(nullValue())); spout.fail(msgIdCaptor.getValue()); reset(consumerMock); when(consumerMock.poll(anyLong())).thenReturn(new ConsumerRecords<>(Collections.singletonMap(partition, SpoutWithMockedConsumerSetupHelper.createRecords(partition, 1, 1)))); spout.nextTuple(); //The consumer should not be seeking to retry the failed tuple, it should just be continuing from the current position verify(consumerMock, never()).seek(eq(partition), anyLong()); }
@Test public void defaultInexType() throws Exception { DistributedMember member = mock(DistributedMember.class); doReturn(Collections.singleton(member)).when(command).findMembers(any(), any()); ArgumentCaptor<RegionConfig.Index> indexTypeCaptor = ArgumentCaptor.forClass(RegionConfig.Index.class); gfshParser.executeAndAssertThat(command, "create index --name=abc --expression=abc --region=abc"); verify(command).executeAndGetFunctionResult(any(), indexTypeCaptor.capture(), eq(Collections.singleton(member))); assertThat(indexTypeCaptor.getValue().getType()).isEqualTo("range"); }
@Test public void testProvidesBitmapFromGivenResourceToWrappedTransformation() { int outWidth = 332; int outHeight = 111; Resource<Bitmap> transformed = Util.mockResource(); when(transformed.get()) .thenReturn(Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888)); when(wrapped.transform(anyContext(), Util.<Bitmap>anyResource(), anyInt(), anyInt())) .thenReturn(transformed); transformation.transform(context, drawableResourceToTransform, outWidth, outHeight); ArgumentCaptor<Resource<Bitmap>> captor = Util.cast(ArgumentCaptor.forClass(Resource.class)); verify(wrapped).transform(anyContext(), captor.capture(), eq(outWidth), eq(outHeight)); assertThat(captor.getValue().get()).isEqualTo(bitmapToTransform); }