org.mockito.stubbing.Answer Java Examples

The following examples show how to use org.mockito.stubbing.Answer. 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 File: MenuEntrySwapperPluginTest.java    From runelite with 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 #2
Source File: CustomPurchasingTest.java    From unity-ads-android with 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 #3
Source File: PriorityStarvingThrottlingProducerTest.java    From fresco with 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 #4
Source File: TestDefaultJMSMessageConverter.java    From mt-flume with 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 #5
Source File: MQClientAPIImplTest.java    From rocketmq with 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 #6
Source File: DynamicTransformServiceTest.java    From pinpoint with 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 #7
Source File: CallCredentialsApplyingTest.java    From grpc-nebula-java with 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 #8
Source File: AmqpClientActorTest.java    From ditto with 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 File: TestZkJobCoordinator.java    From samza with 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 #10
Source File: WisdomSchedulerTest.java    From wisdom with 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 #11
Source File: RORVSystemCommunicationTest.java    From development with 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 #12
Source File: HttpPermissionCheckerImplTest.java    From che with 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 #13
Source File: AuthTest.java    From gdx-fireapp with 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 #14
Source File: HttpPublisherTest.java    From logsniffer with 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 #15
Source File: DefaultMQPullConsumerTest.java    From rocketmq with 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 #16
Source File: ModuleServiceImplTest.java    From alfresco-repository with 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 #17
Source File: PluginRegistryConcurrencyTest.java    From pentaho-kettle with 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 #18
Source File: UserServiceUnitTest.java    From tutorials with 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 #19
Source File: CachedSubchannelPoolTest.java    From grpc-nebula-java with 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 #20
Source File: CustomPurchasingTest.java    From unity-ads-android with 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 File: AuthTest.java    From gdx-fireapp with 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 #22
Source File: AbstractAnnotationBinderTest.java    From byte-buddy with 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 #23
Source File: NettyHandlerTestBase.java    From grpc-nebula-java with 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 #24
Source File: WrapObjectPluginTest.java    From mybatis-generator-plugins with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws Exception {
	plugin = new WrapObjectPlugin();
	plugin.getProperties().put(WrapObjectPlugin.TABLE_NAME, TABLE_NAME);
	plugin.getProperties().put(WrapObjectPlugin.OBJECT_CLASS, OBJECT_CLASS);
	plugin.getProperties().put(WrapObjectPlugin.OBJECT_FIELD_NAME, OBJECT_FIELD_NAME);
	plugin.getProperties().put(WrapObjectPlugin.INCLUDES, INCLUDES);
	plugin.getProperties().put(WrapObjectPlugin.EXCLUDES, EXCLUDES);
	plugin.validate(new ArrayList<String>());

	includeList = new ArrayList<>();
	for (String include : INCLUDES.split(",")) {
		includeList.add(include.trim());
	}
	excludeList = new ArrayList<>();
	for (String exclude : EXCLUDES.split(",")) {
		excludeList.add(exclude.trim());
	}

	methodLines = new ArrayList<>();
	methodLines.add("line1");
	methodLines.add("line2");
	methodLines.add("line3");

	given(method.getBodyLines()).willReturn(methodLines);
	willAnswer(new Answer<Void>() {
		@Override
		public Void answer(InvocationOnMock invocation) throws Throwable {
			methodLines.add(invocation.getArgumentAt(0, String.class));
			return null;
		}
	}).given(method).addBodyLine(anyString());
}
 
Example #25
Source File: TestProcedureMember.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Handle failures if a member's commit phase fails.
 *
 * NOTE: This is the core difference that makes this different from traditional 2PC.  In true
 * 2PC the transaction is committed just before the coordinator sends commit messages to the
 * member.  Members are then responsible for reading its TX log.  This implementation actually
 * rolls back, and thus breaks the normal TX guarantees.
*/
@Test
public void testMemberCommitException() throws Exception {
  buildCohortMemberPair();

  // mock an exception on Subprocedure's prepare
  doAnswer(
      new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
          throw new IOException("Forced IOException in memeber prepare");
        }
      }).when(spySub).insideBarrier();

  // run the operation
  // build a new operation
  Subprocedure subproc = member.createSubprocedure(op, data);
  member.submitSubprocedure(subproc);
  // if the operation doesn't die properly, then this will timeout
  member.closeAndWait(TIMEOUT);

  // make sure everything ran in order
  InOrder order = inOrder(mockMemberComms, spySub);
  order.verify(spySub).acquireBarrier();
  order.verify(mockMemberComms).sendMemberAcquired(eq(spySub));
  order.verify(spySub).insideBarrier();

  // Later phases not run
  order.verify(mockMemberComms, never()).sendMemberCompleted(eq(spySub), eq(data));
  // error recovery path exercised
  order.verify(spySub).cancel(anyString(), any());
  order.verify(spySub).cleanup(any());
}
 
Example #26
Source File: UsageStatisticsReportingSqlMapDaoTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
    initMocks(this);
    reportingSqlMapDao = new UsageStatisticsReportingSqlMapDao(sessionFactory, transactionTemplate, synchronizationManager, goCache);

    internalTestCache = new HashMap<>();
    when(goCache.get(getCacheKey())).then((Answer<UsageStatisticsReporting>) invocation -> (UsageStatisticsReporting) internalTestCache.get(invocation.<String>getArgument(0)));
    doAnswer(invocation -> {
        internalTestCache.put(invocation.getArgument(0), invocation.getArgument(1));
        return null;
    }).when(goCache).put(anyString(), any(UsageStatisticsReporting.class));
    when(goCache.remove(getCacheKey())).then((Answer<UsageStatisticsReporting>) invocation -> (UsageStatisticsReporting) internalTestCache.remove(invocation.<String>getArgument(0)));
}
 
Example #27
Source File: TestHttpClientTransaction.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendButDestinationFull() throws IOException {

    SiteToSiteRestApiClient apiClient = mock(SiteToSiteRestApiClient.class);
    final String transactionUrl = "http://www.example.com/data-transfer/input-ports/portId/transactions/transactionId";
    doNothing().when(apiClient).openConnectionForSend(eq("portId"), any(Peer.class));
    // Emulate that server returns correct checksum.
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            HttpCommunicationsSession commSession = (HttpCommunicationsSession)invocation.getArguments()[0];
            commSession.setChecksum("3359812065");
            return null;
        }
    }).when(apiClient).finishTransferFlowFiles(any(CommunicationsSession.class));
    TransactionResultEntity resultEntity = new TransactionResultEntity();
    resultEntity.setResponseCode(ResponseCode.TRANSACTION_FINISHED_BUT_DESTINATION_FULL.getCode());
    doReturn(resultEntity).when(apiClient).commitTransferFlowFiles(eq(transactionUrl), eq(CONFIRM_TRANSACTION));

    ByteArrayOutputStream serverResponseBos = new ByteArrayOutputStream();
    ByteArrayInputStream serverResponse = new ByteArrayInputStream(serverResponseBos.toByteArray());
    ByteArrayOutputStream clientRequest = new ByteArrayOutputStream();
    HttpClientTransaction transaction = getClientTransaction(serverResponse, clientRequest, apiClient, TransferDirection.SEND, transactionUrl);

    execSendButDestinationFull(transaction);

    InputStream sentByClient = new ByteArrayInputStream(clientRequest.toByteArray());
    DataPacket packetByClient = codec.decode(sentByClient);
    assertEquals("contents on client 1", readContents(packetByClient));
    packetByClient = codec.decode(sentByClient);
    assertEquals("contents on client 2", readContents(packetByClient));
    assertEquals(-1, sentByClient.read());

    verify(apiClient).commitTransferFlowFiles(transactionUrl, CONFIRM_TRANSACTION);
}
 
Example #28
Source File: DataTransportCrashlyticsReportSenderTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private static Answer<Void> callbackAnswer(Exception failure) {
  return (i) -> {
    final TransportScheduleCallback callback = i.getArgument(1);
    callback.onSchedule(failure);
    return null;
  };
}
 
Example #29
Source File: AssessmentResourceTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private void setupMocks(String uri) throws URISyntaxException {
    requestURI = new java.net.URI(uri);

    MultivaluedMap map = new MultivaluedMapImpl();
    uriInfo = mock(UriInfo.class);
    when(uriInfo.getRequestUri()).thenReturn(requestURI);
    when(uriInfo.getQueryParameters()).thenReturn(map);
    when(uriInfo.getBaseUriBuilder()).thenAnswer(new Answer<UriBuilder>() {
        @Override
        public UriBuilder answer(InvocationOnMock invocation) throws Throwable {
            return new UriBuilderImpl().path("base");
        }
    });
}
 
Example #30
Source File: FunctionTest.java    From deployment-examples with MIT License 5 votes vote down vote up
/**
 * Unit test for HttpTriggerJava method.
 */
@Test
public void testHttpTriggerJava() throws Exception {
    // Setup
    @SuppressWarnings("unchecked")
    final HttpRequestMessage<Optional<String>> req = mock(HttpRequestMessage.class);

    final Map<String, String> queryParams = new HashMap<>();
    queryParams.put("name", "Azure");
    doReturn(queryParams).when(req).getQueryParameters();

    final Optional<String> queryBody = Optional.empty();
    doReturn(queryBody).when(req).getBody();

    doAnswer(new Answer<HttpResponseMessage.Builder>() {
        @Override
        public HttpResponseMessage.Builder answer(InvocationOnMock invocation) {
            HttpStatus status = (HttpStatus) invocation.getArguments()[0];
            return new HttpResponseMessageMock.HttpResponseMessageBuilderMock().status(status);
        }
    }).when(req).createResponseBuilder(any(HttpStatus.class));

    final ExecutionContext context = mock(ExecutionContext.class);
    doReturn(Logger.getGlobal()).when(context).getLogger();

    // Invoke
    final HttpResponseMessage ret = new Function().run(req, context);

    // Verify
    assertEquals(ret.getStatus(), HttpStatus.OK);
}