Java Code Examples for org.mockito.stubbing.Answer

The following examples show how to use org.mockito.stubbing.Answer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: rocketmq   Author: apache   File: MQClientAPIImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@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");
    }
}
 
Example #2
Source Project: rocketmq   Author: JiangJibo   File: DefaultMQPullConsumerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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<>());
}
 
Example #3
Source Project: grpc-nebula-java   Author: grpc-nebula   File: CachedSubchannelPoolTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source Project: grpc-nebula-java   Author: grpc-nebula   File: NettyHandlerTestBase.java    License: Apache License 2.0 6 votes vote down vote up
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));
}
 
Example #5
Source Project: gdx-fireapp   Author: mk-5   File: AuthTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #6
Source Project: grpc-nebula-java   Author: grpc-nebula   File: CallCredentialsApplyingTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #7
Source Project: unity-ads-android   Author: Unity-Technologies   File: CustomPurchasingTest.java    License: Apache License 2.0 6 votes vote down vote up
@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))));
}
 
Example #8
Source Project: ditto   Author: eclipse   File: AmqpClientActorTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
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());
}
 
Example #9
Source Project: gdx-fireapp   Author: mk-5   File: AuthTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #10
Source Project: tutorials   Author: eugenp   File: UserServiceUnitTest.java    License: MIT License 6 votes vote down vote up
@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);
}
 
Example #11
Source Project: alfresco-repository   Author: Alfresco   File: ModuleServiceImplTest.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #12
Source Project: runelite   Author: runelite   File: MenuEntrySwapperPluginTest.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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();
}
 
Example #13
Source Project: pentaho-kettle   Author: pentaho   File: PluginRegistryConcurrencyTest.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #14
Source Project: byte-buddy   Author: raphw   File: AbstractAnnotationBinderTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #15
Source Project: mt-flume   Author: javachen   File: TestDefaultJMSMessageConverter.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #16
Source Project: samza   Author: apache   File: TestZkJobCoordinator.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #17
Source Project: wisdom   Author: wisdom-framework   File: WisdomSchedulerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #18
Source Project: che   Author: eclipse   File: HttpPermissionCheckerImplTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #19
Source Project: logsniffer   Author: mbok   File: HttpPublisherTest.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #20
Source Project: unity-ads-android   Author: Unity-Technologies   File: CustomPurchasingTest.java    License: Apache License 2.0 6 votes vote down vote up
@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))));
}
 
Example #21
Source Project: pinpoint   Author: naver   File: DynamicTransformServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #22
Source Project: fresco   Author: facebook   File: PriorityStarvingThrottlingProducerTest.java    License: MIT License 6 votes vote down vote up
@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]));
  }
}
 
Example #23
Source Project: development   Author: servicecatalog   File: RORVSystemCommunicationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #24
Source Project: spring-cloud-aws   Author: spring-cloud   File: SimpleStorageResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@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
}
 
Example #25
Source Project: DeFiBus   Author: WeBankFinTech   File: DeFiBusClientAPIImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #26
Source Project: xbee-java   Author: digidotcom   File: XBeePacketsQueueTest.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #27
Source Project: incubator-atlas   Author: apache   File: AtlasEntityStoreV1BulkImportPercentTest.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #28
Source Project: pentaho-kettle   Author: pentaho   File: BaseStepTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #29
Source Project: flink   Author: flink-tpc-ds   File: WindowOperatorContractTest.java    License: Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #30
Source Project: hadoop   Author: naver   File: TestLeafQueue.java    License: Apache License 2.0 5 votes vote down vote up
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;
}