java.nio.channels.AsynchronousByteChannel#org.mockito.stubbing.Answer源码实例Demo

下面列出了java.nio.channels.AsynchronousByteChannel#org.mockito.stubbing.Answer 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: rocketmq   文件: MQClientAPIImplTest.java
@Test
public void testCreatePlainAccessConfig_Exception() throws InterruptedException, RemotingException, MQBrokerException {

    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock mock) throws Throwable {
            RemotingCommand request = mock.getArgument(1);
            return createErrorResponse4UpdateAclConfig(request);
        }
    }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());

    PlainAccessConfig config = createUpdateAclConfig();
    try {
        mqClientAPI.createPlainAccessConfig(brokerAddr, config, 3 * 1000);
    } catch (MQClientException ex) {
        assertThat(ex.getResponseCode()).isEqualTo(209);
        assertThat(ex.getErrorMessage()).isEqualTo("corresponding to accessConfig has been updated failed");
    }
}
 
源代码2 项目: rocketmq   文件: DefaultMQPullConsumerTest.java
@Test
public void testPullMessage_Success() throws Exception {
    doAnswer(new Answer() {
        @Override public Object answer(InvocationOnMock mock) throws Throwable {
            PullMessageRequestHeader requestHeader = mock.getArgument(1);
            return createPullResult(requestHeader, PullStatus.FOUND, Collections.singletonList(new MessageExt()));
        }
    }).when(mQClientAPIImpl).pullMessage(anyString(), any(PullMessageRequestHeader.class), anyLong(), any(CommunicationMode.class), nullable(PullCallback.class));

    MessageQueue messageQueue = new MessageQueue(topic, brokerName, 0);
    PullResult pullResult = pullConsumer.pull(messageQueue, "*", 1024, 3);
    assertThat(pullResult).isNotNull();
    assertThat(pullResult.getPullStatus()).isEqualTo(PullStatus.FOUND);
    assertThat(pullResult.getNextBeginOffset()).isEqualTo(1024 + 1);
    assertThat(pullResult.getMinOffset()).isEqualTo(123);
    assertThat(pullResult.getMaxOffset()).isEqualTo(2048);
    assertThat(pullResult.getMsgFoundList()).isEqualTo(new ArrayList<>());
}
 
@Before
@SuppressWarnings("unchecked")
public void setUp() {
  doAnswer(new Answer<Subchannel>() {
      @Override
      public Subchannel answer(InvocationOnMock invocation) throws Throwable {
        Subchannel subchannel = mock(Subchannel.class);
        List<EquivalentAddressGroup> eagList =
            (List<EquivalentAddressGroup>) invocation.getArguments()[0];
        Attributes attrs = (Attributes) invocation.getArguments()[1];
        when(subchannel.getAllAddresses()).thenReturn(eagList);
        when(subchannel.getAttributes()).thenReturn(attrs);
        mockSubchannels.add(subchannel);
        return subchannel;
      }
    }).when(helper).createSubchannel(any(List.class), any(Attributes.class));
  when(helper.getSynchronizationContext()).thenReturn(syncContext);
  when(helper.getScheduledExecutorService()).thenReturn(clock.getScheduledExecutorService());
  pool.init(helper);
}
 
源代码4 项目: grpc-nebula-java   文件: NettyHandlerTestBase.java
void createEventLoop() {
  EventLoop realEventLoop = super.eventLoop();
  if (realEventLoop == null) {
    return;
  }
  eventLoop = mock(EventLoop.class, delegatesTo(realEventLoop));
  doAnswer(
      new Answer<ScheduledFuture<Void>>() {
        @Override
        public ScheduledFuture<Void> answer(InvocationOnMock invocation) throws Throwable {
          Runnable command = (Runnable) invocation.getArguments()[0];
          Long delay = (Long) invocation.getArguments()[1];
          TimeUnit timeUnit = (TimeUnit) invocation.getArguments()[2];
          return new FakeClockScheduledNettyFuture(eventLoop, command, delay, timeUnit);
        }
      }).when(eventLoop).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
}
 
源代码5 项目: gdx-fireapp   文件: AuthTest.java
@Test
public void signInWithToken() {
    // Given
    Mockito.doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            ((FIRAuth.Block_signInWithCustomTokenCompletion) invocation.getArgument(1)).call_signInWithCustomTokenCompletion(null, null);
            return null;
        }
    }).when(firAuth).signInWithCustomTokenCompletion(Mockito.anyString(), Mockito.any());
    Auth auth = new Auth();

    // When
    auth.signInWithToken("token").subscribe(consumer);

    // Then
    Mockito.verify(firAuth, VerificationModeFactory.times(1)).signInWithCustomTokenCompletion(Mockito.eq("token"), Mockito.any());
    Mockito.verify(consumer, VerificationModeFactory.times(1)).accept(Mockito.nullable(GdxFirebaseUser.class));
}
 
@Test
public void applyMetadata_inline() {
  when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY);
  doAnswer(new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
        CallCredentials.MetadataApplier applier =
            (CallCredentials.MetadataApplier) invocation.getArguments()[3];
        Metadata headers = new Metadata();
        headers.put(CREDS_KEY, CREDS_VALUE);
        applier.apply(headers);
        return null;
      }
    }).when(mockCreds).applyRequestMetadata(same(method), any(Attributes.class),
        same(mockExecutor), any(CallCredentials.MetadataApplier.class));

  ClientStream stream = transport.newStream(method, origHeaders, callOptions);

  verify(mockTransport).newStream(method, origHeaders, callOptions);
  assertSame(mockStream, stream);
  assertEquals(CREDS_VALUE, origHeaders.get(CREDS_KEY));
  assertEquals(ORIG_HEADER_VALUE, origHeaders.get(ORIG_HEADER_KEY));
}
 
源代码7 项目: unity-ads-android   文件: CustomPurchasingTest.java
@Test
public void onTransactionErrorShouldSendTransactionErrorEventToWebView() {
    final TransactionErrorDetails detail = TransactionErrorDetails.newBuilder()
            .withStore(Store.GOOGLE_PLAY)
            .withTransactionError(TransactionError.ITEM_UNAVAILABLE)
            .withExceptionMessage("test exception")
            .withStoreSpecificErrorCode("google failed")
            .build();
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            ITransactionListener listener = invocation.getArgument(1);
            listener.onTransactionError(detail);
            return null;
        }
    }).when(purchasingAdapter).onPurchase(eq(Fixture.productID), any(ITransactionListener.class), eq(JSONUtilities.jsonObjectToMap(Fixture.purchaseExtras)));

    WebViewCallback callback = mock(WebViewCallback.class);
    CustomPurchasing.purchaseItem(Fixture.productID, Fixture.purchaseExtras, callback);

    ;
    verify(webViewApp).sendEvent(eq(WebViewEventCategory.CUSTOM_PURCHASING),
            eq(PurchasingEvent.TRANSACTION_ERROR),
            argThat(new JsonObjectMatcher(TransactionErrorDetailsUtilities.getJSONObjectForTransactionErrorDetails(detail))));
}
 
源代码8 项目: ditto   文件: AmqpClientActorTest.java
private void prepareSession(final Session mockSession, final JmsMessageConsumer mockConsumer) throws JMSException {
    doReturn(mockConsumer).when(mockSession).createConsumer(any(JmsQueue.class));
    doAnswer((Answer<MessageProducer>) destinationInv -> {
        final MessageProducer messageProducer = mock(MessageProducer.class);
        doReturn(destinationInv.getArgument(0)).when(messageProducer).getDestination();
        mockProducers.add(messageProducer);
        return messageProducer;
    }).when(mockSession).createProducer(any(Destination.class));
    doAnswer((Answer<JmsMessage>) textMsgInv -> {
        final String textMsg = textMsgInv.getArgument(0);
        final AmqpJmsTextMessageFacade facade = new AmqpJmsTextMessageFacade();
        facade.initialize(Mockito.mock(AmqpConnection.class));
        final JmsTextMessage jmsTextMessage = new JmsTextMessage(facade);
        jmsTextMessage.setText(textMsg);
        return jmsTextMessage;
    }).when(mockSession).createTextMessage(anyString());
}
 
源代码9 项目: gdx-fireapp   文件: AuthTest.java
@Test
public void sendPasswordResetEmail() {
    // Given
    PowerMockito.mockStatic(PtrFactory.class);
    Mockito.doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            ((FIRAuth.Block_sendPasswordResetWithEmailCompletion) invocation.getArgument(1))
                    .call_sendPasswordResetWithEmailCompletion(null);
            return null;
        }
    }).when(firAuth).sendPasswordResetWithEmailCompletion(Mockito.anyString(), Mockito.any());
    Auth auth = new Auth();
    String arg1 = "email";

    // When
    auth.sendPasswordResetEmail(arg1).subscribe(consumer);

    // Then
    Mockito.verify(firAuth, VerificationModeFactory.times(1)).sendPasswordResetWithEmailCompletion(Mockito.eq(arg1), Mockito.any());
    Mockito.verify(consumer, VerificationModeFactory.times(1)).accept(Mockito.any());
}
 
源代码10 项目: tutorials   文件: UserServiceUnitTest.java
@Test
void givenValidUser_whenSaveUser_thenSucceed(@Mock MailClient mailClient) {
    // Given
    user = new User("Jerry", 12);
    when(userRepository.insert(any(User.class))).then(new Answer<User>() {
        int sequence = 1;
        
        @Override
        public User answer(InvocationOnMock invocation) throws Throwable {
            User user = (User) invocation.getArgument(0);
            user.setId(sequence++);
            return user;
        }
    });

    userService = new DefaultUserService(userRepository, settingRepository, mailClient);

    // When
    User insertedUser = userService.register(user);
    
    // Then
    verify(userRepository).insert(user);
    Assertions.assertNotNull(user.getId());
    verify(mailClient).sendUserRegistrationMail(insertedUser);
}
 
@Before
public void setUp() throws Exception
{
    moduleService = new ModuleServiceImpl();
    Resource simpleMod = new PathMatchingResourcePatternResolver().getResource("classpath:alfresco/module/simplemodule.properties");
    assertNotNull(simpleMod);
    RegistryService reg = mock(RegistryService.class);
    ApplicationContext applicationContext = mock(ApplicationContext.class);

    when(reg.getProperty((RegistryKey) any())).thenAnswer(new Answer<Serializable>()
    {
        public Serializable answer(InvocationOnMock invocation) throws Throwable
        {
            RegistryKey key = (RegistryKey) invocation.getArguments()[0];
            return new ModuleVersionNumber("1.1");
        }
    });
    doReturn(Arrays.asList("fee", "alfresco-simple-module", "fo")).when(reg).getChildElements((RegistryKey) any());
    doReturn(new Resource[] {simpleMod}).when(applicationContext).getResources(anyString());
    moduleService.setRegistryService(reg);
    moduleService.setApplicationContext(applicationContext);
}
 
源代码12 项目: runelite   文件: MenuEntrySwapperPluginTest.java
@Before
public void before()
{
	Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this);

	when(client.getGameState()).thenReturn(GameState.LOGGED_IN);

	when(client.getMenuEntries()).thenAnswer((Answer<MenuEntry[]>) invocationOnMock ->
	{
		// The menu implementation returns a copy of the array, which causes swap() to not
		// modify the same array being iterated in onClientTick
		MenuEntry[] copy = new MenuEntry[entries.length];
		System.arraycopy(entries, 0, copy, 0, entries.length);
		return copy;
	});
	doAnswer((Answer<Void>) invocationOnMock ->
	{
		Object argument = invocationOnMock.getArguments()[0];
		entries = (MenuEntry[]) argument;
		return null;
	}).when(client).setMenuEntries(any(MenuEntry[].class));

	menuEntrySwapperPlugin.setupSwaps();
}
 
@Override
Object doCall() throws Exception {
  List<PluginInterface> registered = new ArrayList<PluginInterface>( cycles );
  try {
    for ( int i = 0; i < cycles; i++ ) {
      String id = nameSeed + '_' + i;
      PluginInterface mock = mock( PluginInterface.class );
      when( mock.getName() ).thenReturn( id );
      when( mock.getIds() ).thenReturn( new String[] { id } );
      when( mock.getPluginType() ).thenAnswer( new Answer<Object>() {
        @Override public Object answer( InvocationOnMock invocation ) throws Throwable {
          return type;
        }
      } );

      registered.add( mock );

      PluginRegistry.getInstance().registerPlugin( type, mock );
    }
  } finally {
    // push up registered instances for future clean-up
    addUsedPlugins( type, registered );
  }
  return null;
}
 
源代码14 项目: byte-buddy   文件: AbstractAnnotationBinderTest.java
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(sourceDeclaringType.asErasure()).thenReturn(sourceDeclaringType);
    when(targetDeclaringType.asErasure()).thenReturn(targetDeclaringType);
    when(source.getDeclaringType()).thenReturn(sourceDeclaringType);
    annotation = mock(annotationType);
    doReturn(annotationType).when(annotation).annotationType();
    annotationDescription = AnnotationDescription.ForLoadedAnnotation.of(annotation);
    when(assigner.assign(any(TypeDescription.Generic.class), any(TypeDescription.Generic.class), any(Assigner.Typing.class))).thenReturn(stackManipulation);
    when(implementationTarget.getInstrumentedType()).thenReturn(instrumentedType);
    when(implementationTarget.getOriginType()).thenReturn(instrumentedType);
    when(instrumentedType.asErasure()).thenReturn(instrumentedType);
    when(instrumentedType.iterator()).then(new Answer<Iterator<TypeDefinition>>() {
        public Iterator<TypeDefinition> answer(InvocationOnMock invocationOnMock) throws Throwable {
            return Collections.<TypeDefinition>singleton(instrumentedType).iterator();
        }
    });
    when(source.asTypeToken()).thenReturn(sourceTypeToken);
}
 
源代码15 项目: mt-flume   文件: TestDefaultJMSMessageConverter.java
void createBytesMessage() throws Exception {
  BytesMessage message = mock(BytesMessage.class);
  when(message.getBodyLength()).thenReturn((long)BYTES.length);
  when(message.readBytes(any(byte[].class))).then(new Answer<Integer>() {
    @Override
    public Integer answer(InvocationOnMock invocation) throws Throwable {
      byte[] buffer = (byte[])invocation.getArguments()[0];
      if(buffer != null) {
        assertEquals(buffer.length, BYTES.length);
        System.arraycopy(BYTES, 0, buffer, 0, BYTES.length);
      }
      return BYTES.length;
    }
  });
  this.message = message;
}
 
源代码16 项目: samza   文件: TestZkJobCoordinator.java
@Test
public void testFollowerShouldStopWhenNotPartOfGeneratedJobModel() throws Exception {
  ZkKeyBuilder keyBuilder = Mockito.mock(ZkKeyBuilder.class);
  ZkClient mockZkClient = Mockito.mock(ZkClient.class);
  CountDownLatch jcShutdownLatch = new CountDownLatch(1);
  when(keyBuilder.getJobModelVersionBarrierPrefix()).thenReturn(TEST_BARRIER_ROOT);

  ZkUtils zkUtils = Mockito.mock(ZkUtils.class);
  when(zkUtils.getKeyBuilder()).thenReturn(keyBuilder);
  when(zkUtils.getZkClient()).thenReturn(mockZkClient);

  ZkJobCoordinator zkJobCoordinator = Mockito.spy(new ZkJobCoordinator("TEST_PROCESSOR_ID", new MapConfig(),
      new NoOpMetricsRegistry(), zkUtils, zkMetadataStore, coordinatorStreamStore));
  doReturn(new JobModel(new MapConfig(), new HashMap<>())).when(zkJobCoordinator).readJobModelFromMetadataStore(TEST_JOB_MODEL_VERSION);
  doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
      jcShutdownLatch.countDown();
      return null;
    }
  }).when(zkJobCoordinator).stop();

  final ZkJobCoordinator.ZkJobModelVersionChangeHandler zkJobModelVersionChangeHandler = zkJobCoordinator.new ZkJobModelVersionChangeHandler(zkUtils);
  zkJobModelVersionChangeHandler.doHandleDataChange("path", TEST_JOB_MODEL_VERSION);
  verify(zkJobCoordinator, Mockito.atMost(1)).stop();
  assertTrue("Timed out waiting for JobCoordinator to stop", jcShutdownLatch.await(1, TimeUnit.MINUTES));
}
 
源代码17 项目: wisdom   文件: WisdomSchedulerTest.java
@Before
public void setUp() throws ClassNotFoundException {
    BundleContext context = mock(BundleContext.class);
    Bundle bundle = mock(Bundle.class);
    when(bundle.getBundleId()).thenReturn(1L);
    when(context.getBundle()).thenReturn(bundle);
    doAnswer(
            new Answer<Class>() {
                @Override
                public Class answer(InvocationOnMock invocation) throws Throwable {
                    return WisdomSchedulerTest.class.getClassLoader().loadClass((String) invocation.getArguments()[0]);
                }
            }
    ).when(bundle).loadClass(anyString());
    scheduler.scheduler = new ManagedScheduledExecutorServiceImpl("test",
            new FakeConfiguration(Collections.<String, Object>emptyMap()), null);
}
 
源代码18 项目: che   文件: HttpPermissionCheckerImplTest.java
@BeforeMethod
public void setUp() throws Exception {
  request =
      mock(
          HttpJsonRequest.class,
          (Answer)
              invocation -> {
                if (invocation.getMethod().getReturnType().isInstance(invocation.getMock())) {
                  return invocation.getMock();
                }
                return RETURNS_DEFAULTS.answer(invocation);
              });
  when(request.request()).thenReturn(response);
  when(requestFactory.fromUrl(anyString())).thenReturn(request);

  httpPermissionChecker = new HttpPermissionCheckerImpl(API_ENDPOINT, requestFactory);
}
 
源代码19 项目: logsniffer   文件: HttpPublisherTest.java
@Before
public void setUp() {
	publisher = new HttpPublisher();
	renderer = Mockito.mock(VelocityEventRenderer.class);
	Mockito.when(
			renderer.render(Mockito.anyString(),
					Mockito.any(VelocityContext.class))).thenAnswer(
			new Answer<String>() {

				@Override
				public String answer(final InvocationOnMock invocation)
						throws Throwable {
					return invocation.getArguments()[0].toString();
				}
			});
	client = HttpClientBuilder.create().build();
	publisher.init(renderer, client);
}
 
源代码20 项目: unity-ads-android   文件: CustomPurchasingTest.java
@Test
public void retrieveCatalogShouldSendCatalogEventToWebView() {
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            IRetrieveProductsListener listener = invocation.getArgument(0);
            listener.onProductsRetrieved(Fixture.products);
            return null;
        }
    }).when(purchasingAdapter).retrieveProducts(any(IRetrieveProductsListener.class));

    WebViewCallback callback = mock(WebViewCallback.class);
    CustomPurchasing.refreshCatalog(callback);

    verify(webViewApp).sendEvent(eq(WebViewEventCategory.CUSTOM_PURCHASING),
            eq(PurchasingEvent.PRODUCTS_RETRIEVED),
            argThat(new JsonArrayMatcher(CustomPurchasing.getJSONArrayFromProductList(Fixture.products))));
}
 
源代码21 项目: pinpoint   文件: DynamicTransformServiceTest.java
@Test()
public void testRetransform_Fail_memoryleak_prevent() throws Exception {
    final Instrumentation instrumentation = mock(Instrumentation.class);
    when(instrumentation.isModifiableClass(any(Class.class))).thenReturn(true);
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            throw new UnmodifiableClassException();
        }
    }).when(instrumentation).retransformClasses(any(Class.class));


    DefaultDynamicTransformerRegistry listener = new DefaultDynamicTransformerRegistry();

    final ClassFileTransformer classFileTransformer = mock(ClassFileTransformer.class);

    DynamicTransformService dynamicTransformService = new DynamicTransformService(instrumentation, listener);

    try {
        dynamicTransformService.retransform(String.class, classFileTransformer);
        Assert.fail("expected retransform fail");
    } catch (Exception e) {
    }
    Assert.assertEquals(listener.size(), 0);
}
 
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  mThrottlingProducer =
      new PriorityStarvingThrottlingProducer<>(
          MAX_SIMULTANEOUS_REQUESTS, CallerThreadExecutor.getInstance(), mInputProducer);
  for (int i = 0; i < 7; i++) {
    mConsumers[i] = mock(Consumer.class);
    mProducerContexts[i] = mock(ProducerContext.class);
    mProducerListeners[i] = mock(ProducerListener2.class);
    mResults[i] = mock(Object.class);
    when(mProducerContexts[i].getProducerListener()).thenReturn(mProducerListeners[i]);
    when(mProducerContexts[i].getId()).thenReturn(mRequestIds[i]);
    final int iFinal = i;
    doAnswer(
            new Answer() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                mThrottlerConsumers[iFinal] = (Consumer<Object>) invocation.getArguments()[0];
                return null;
              }
            })
        .when(mInputProducer)
        .produceResults(any(Consumer.class), eq(mProducerContexts[i]));
  }
}
 
源代码23 项目: development   文件: RORVSystemCommunicationTest.java
@Test
public void stopAllVServers() throws Exception {
    // given
    LServerClient serverClient = prepareServerClientForStartStopServers();
    mockConfigurationWithServers();
    final Stack<String> stati = new Stack<>();
    stati.push(VServerStatus.RUNNING);
    stati.push(VServerStatus.STARTING);
    stati.push(VServerStatus.STOPPED);
    doAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            if (!stati.isEmpty()) {
                return stati.pop();
            }
            return VServerStatus.ERROR;
        }
    }).when(serverClient).getStatus();

    // when
    rorVSystemCommunication.stopAllVServers(ph);
}
 
@Test
void writeFile_forNewFile_writesFileContent() throws Exception {
	// Arrange
	AmazonS3 amazonS3 = mock(AmazonS3.class);
	SimpleStorageResource simpleStorageResource = new SimpleStorageResource(amazonS3,
			"bucketName", "objectName", new SyncTaskExecutor());
	String messageContext = "myFileContent";
	when(amazonS3.putObject(eq("bucketName"), eq("objectName"),
			any(InputStream.class), any(ObjectMetadata.class)))
					.thenAnswer((Answer<PutObjectResult>) invocation -> {
						assertThat(invocation.getArguments()[0])
								.isEqualTo("bucketName");
						assertThat(invocation.getArguments()[1])
								.isEqualTo("objectName");
						byte[] content = new byte[messageContext.length()];
						assertThat(((InputStream) invocation.getArguments()[2])
								.read(content)).isEqualTo(content.length);
						assertThat(new String(content)).isEqualTo(messageContext);
						return new PutObjectResult();
					});
	OutputStream outputStream = simpleStorageResource.getOutputStream();

	// Act
	outputStream.write(messageContext.getBytes());
	outputStream.flush();
	outputStream.close();

	// Assert
}
 
源代码25 项目: DeFiBus   文件: DeFiBusClientAPIImplTest.java
@Test(expected = MQBrokerException.class)
public void testGetConsumerIdListByGroupAndTopic_OnException() throws Exception {
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock mock) throws Throwable {
            RemotingCommand request = mock.getArgument(1);
            request.setCode(ResponseCode.SYSTEM_ERROR);
            return request;
        }
    }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());
    deFiBusClientAPI.getConsumerIdListByGroupAndTopic(brokerAddr, group, topic, 3 * 1000);
}
 
源代码26 项目: xbee-java   文件: XBeePacketsQueueTest.java
/**
 * Test method for {@link com.digi.xbee.api.models.XBeePacketsQueue#getFirstPacket(int)}.
 * 
 * <p>Verify that when requesting the first packet of the queue with a timeout greater than 
 * 0 and the queue is empty, the timeout elapses and a null packet is received.</p>
 * 
 * @throws Exception 
 */
@Test
public void testGetFirstPacketTimeout() throws Exception {
	// Create an XBeePacketsQueue of 5 slots but don't fill it.
	XBeePacketsQueue xbeePacketsQueue = PowerMockito.spy(new XBeePacketsQueue(5));
	
	// Get the current time.
	currentMillis = System.currentTimeMillis();
	
	// Prepare the System class to return our fixed currentMillis variable when requested.
	PowerMockito.mockStatic(System.class);
	PowerMockito.when(System.currentTimeMillis()).thenReturn(currentMillis);
	
	// When the sleep method is called, add 100ms to the currentMillis variable.
	PowerMockito.doAnswer(new Answer<Object>() {
		public Object answer(InvocationOnMock invocation) throws Exception {
			Object[] args = invocation.getArguments();
			int sleepTime = (Integer)args[0];
			changeMillisToReturn(sleepTime);
			return null;
		}
	}).when(xbeePacketsQueue, METHOD_SLEEP, Mockito.anyInt());
	
	// Request the first packet with 5s of timeout.
	XBeePacket xbeePacket = xbeePacketsQueue.getFirstPacket(5000);
	
	// Verify that the sleep method was called 50 times (50 * 100ms = 5s) and the packet 
	// retrieved is null.
	PowerMockito.verifyPrivate(xbeePacketsQueue, Mockito.times(50)).invoke(METHOD_SLEEP, 100);
	assertNull(xbeePacket);
}
 
@BeforeClass
void mockLog() {
    log = mock(Logger.class);

    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Object[] args = invocationOnMock.getArguments();
            Integer d = (Integer) args[1];
            percentHolder.add(d.intValue());
            return null;
        }
    }).when(log).info(anyString(), anyFloat(), anyInt(), anyString());
}
 
源代码28 项目: pentaho-kettle   文件: BaseStepTest.java
@Test
public void testBaseStepGetLogLevelWontThrowNPEWithNullLog() {
  when( mockHelper.logChannelInterfaceFactory.create( any(), any( LoggingObjectInterface.class ) ) ).thenAnswer(
    new Answer<LogChannelInterface>() {

      @Override
      public LogChannelInterface answer( InvocationOnMock invocation ) throws Throwable {
        ( (BaseStep) invocation.getArguments()[ 0 ] ).getLogLevel();
        return mockHelper.logChannelInterface;
      }
    } );
  new BaseStep( mockHelper.stepMeta, mockHelper.stepDataInterface, 0, mockHelper.transMeta, mockHelper.trans )
    .getLogLevel();
}
 
源代码29 项目: flink   文件: WindowOperatorContractTest.java
private static <T> void shouldDeleteProcessingTimeTimerOnElement(Trigger<T, TimeWindow> mockTrigger, final long timestamp) throws Exception {
	doAnswer(new Answer<TriggerResult>() {
		@Override
		public TriggerResult answer(InvocationOnMock invocation) throws Exception {
			@SuppressWarnings("unchecked")
			Trigger.TriggerContext context =
					(Trigger.TriggerContext) invocation.getArguments()[3];
			context.deleteProcessingTimeTimer(timestamp);
			return TriggerResult.CONTINUE;
		}
	})
			.when(mockTrigger).onElement(Matchers.<T>anyObject(), anyLong(), anyTimeWindow(), anyTriggerContext());
}
 
源代码30 项目: hadoop   文件: TestLeafQueue.java
static LeafQueue stubLeafQueue(LeafQueue queue) {
  
  // Mock some methods for ease in these unit tests
  
  // 1. LeafQueue.createContainer to return dummy containers
  doAnswer(
      new Answer<Container>() {
        @Override
        public Container answer(InvocationOnMock invocation) 
            throws Throwable {
          final FiCaSchedulerApp application = 
              (FiCaSchedulerApp)(invocation.getArguments()[0]);
          final ContainerId containerId =                 
              TestUtils.getMockContainerId(application);

          Container container = TestUtils.getMockContainer(
              containerId,
              ((FiCaSchedulerNode)(invocation.getArguments()[1])).getNodeID(), 
              (Resource)(invocation.getArguments()[2]),
              ((Priority)invocation.getArguments()[3]));
          return container;
        }
      }
    ).
    when(queue).createContainer(
            any(FiCaSchedulerApp.class), 
            any(FiCaSchedulerNode.class), 
            any(Resource.class),
            any(Priority.class)
            );
  
  // 2. Stub out LeafQueue.parent.completedContainer
  CSQueue parent = queue.getParent();
  doNothing().when(parent).completedContainer(
      any(Resource.class), any(FiCaSchedulerApp.class), any(FiCaSchedulerNode.class), 
      any(RMContainer.class), any(ContainerStatus.class), 
      any(RMContainerEventType.class), any(CSQueue.class), anyBoolean());
  
  return queue;
}