Java Code Examples for org.mockito.invocation.InvocationOnMock

The following are top voted examples for showing how to use org.mockito.invocation.InvocationOnMock. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: q-mail   File: WebDavStoreTest.java   Source Code and License 9 votes vote down vote up
private Answer<HttpResponse> createOkResponseWithCookie() {
    return new Answer<HttpResponse>() {
        @Override
        public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
            HttpContext context = (HttpContext) invocation.getArguments()[1];
            if (context.getAttribute(ClientContext.COOKIE_STORE) != null) {
                BasicCookieStore cookieStore =
                        (BasicCookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
                BasicClientCookie cookie = new BasicClientCookie("cookie", "meLikeCookie");
                cookieStore.addCookie(cookie);
            }

            return OK_200_RESPONSE;
        }
    };
}
 
Example 2
Project: hadoop   File: TestBlockToken.java   Source Code and License 7 votes vote down vote up
@Override
public GetReplicaVisibleLengthResponseProto answer(
    InvocationOnMock invocation) throws IOException {
  Object args[] = invocation.getArguments();
  assertEquals(2, args.length);
  GetReplicaVisibleLengthRequestProto req = 
      (GetReplicaVisibleLengthRequestProto) args[1];
  Set<TokenIdentifier> tokenIds = UserGroupInformation.getCurrentUser()
      .getTokenIdentifiers();
  assertEquals("Only one BlockTokenIdentifier expected", 1, tokenIds.size());
  long result = 0;
  for (TokenIdentifier tokenId : tokenIds) {
    BlockTokenIdentifier id = (BlockTokenIdentifier) tokenId;
    LOG.info("Got: " + id.toString());
    assertTrue("Received BlockTokenIdentifier is wrong", ident.equals(id));
    sm.checkAccess(id, null, PBHelper.convert(req.getBlock()),
        BlockTokenSecretManager.AccessMode.WRITE);
    result = id.getBlockId();
  }
  return GetReplicaVisibleLengthResponseProto.newBuilder()
      .setLength(result).build();
}
 
Example 3
Project: pcloud-networking-java   File: RealCallTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSuccessfulEnqueueReportsResultToTheCallback() throws Exception {
    Endpoint endpoint = new Endpoint(MOCK_HOST, MOCK_PORT);
    final Connection connection = createDummyConnection(endpoint, MOCK_EMPTY_ARRAY_RESPONSE);
    Request request = RequestUtils.getUserInfoRequest(endpoint);
    mockConnection(connection);

    final RealCall call = getMockRealCall(request, executor);

    Callback callback = mock(Callback.class);
    when(executor.submit(any(Runnable.class))).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            Runnable runnable = (Runnable) args[0];
            runnable.run();
            return new FutureTask<Void>(runnable, null);
        }
    });

    call.enqueue(callback);

    verify(callback).onResponse(eq(call), notNull(Response.class));
    verify(callback, never()).onFailure(eq(call), notNull(IOException.class));
}
 
Example 4
Project: q-mail   File: MessagingControllerTest.java   Source Code and License 6 votes vote down vote up
private void respondToFetchEnvelopesWithMessage(final Message message) throws MessagingException {
    doAnswer(new Answer() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            FetchProfile fetchProfile = (FetchProfile) invocation.getArguments()[1];
            if (invocation.getArguments()[2] != null) {
                MessageRetrievalListener listener = (MessageRetrievalListener) invocation.getArguments()[2];
                if (fetchProfile.contains(FetchProfile.Item.ENVELOPE)) {
                    listener.messageStarted("UID", 1, 1);
                    listener.messageFinished(message, 1, 1);
                    listener.messagesFinished(1);
                }
            }
            return null;
        }
    }).when(remoteFolder).fetch(any(List.class), any(FetchProfile.class), any(MessageRetrievalListener.class));
}
 
Example 5
Project: empiria.player   File: PowerFeedbackMediatorTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private void initEventHandlersInterception() {
    doAnswer(new Answer<Void>() {

        final EventType<StateChangeEventHandler, StateChangeEventTypes> STATE_CHANGED_TYPE = StateChangeEvent.getType(OUTCOME_STATE_CHANGED);
        final EventType<PlayerEventHandler, PlayerEventTypes> PAGE_UNLOADED_TYPE = PlayerEvent.getType(PlayerEventTypes.PAGE_UNLOADED);
        final EventType<PlayerEventHandler, PlayerEventTypes> TEST_PAGE_LOADED_TYPE = PlayerEvent.getType(PlayerEventTypes.TEST_PAGE_LOADED);

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            EventType type = (EventType) invocation.getArguments()[0];
            Object handler = invocation.getArguments()[1];

            if (handler instanceof StateChangeEventHandler && type == STATE_CHANGED_TYPE) {
                stateChangedHandler = (StateChangeEventHandler) handler;
            } else if (handler instanceof PlayerEventHandler && type == PAGE_UNLOADED_TYPE) {
                pageUnloadedhandler = (PlayerEventHandler) handler;
            } else if (handler instanceof PlayerEventHandler && type == TEST_PAGE_LOADED_TYPE) {
                testPageLoadedHandler = (PlayerEventHandler) handler;
            }

            return null;
        }
    }).when(eventsBus).addHandler(any(EventType.class), any(EventHandler.class), any(EventScope.class));
}
 
Example 6
Project: QuizZz   File: QuestionServiceTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testAddAnswerToQuestion_firstAnswer_shouldEnableQuestionAndMarkItAsCorrect() {
	when(answerService.countAnswersInQuestion(question)).thenReturn(0);
	question.setIsValid(false);
	question.setCorrectAnswer(null);
	Answer answer = new Answer();
	answer.setId(1l);

	when(answerService.save(any(Answer.class))).thenAnswer(new org.mockito.stubbing.Answer<Answer>() {
		@Override
		public Answer answer(InvocationOnMock invocation) throws Throwable {
			Object[] args = invocation.getArguments();
			return (Answer) args[0];
		}
	});

	service.addAnswerToQuestion(answer, question);

	assertTrue(question.getIsValid());
	assertEquals(answer, question.getCorrectAnswer());
	verify(answerService, times(1)).save(answer);
	verify(questionRepository, times(2)).save(question);
}
 
Example 7
Project: kubernetes-elastic-agents   File: KubernetesAgentInstancesIntegrationTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    initMocks(this);
    kubernetesAgentInstances = new KubernetesAgentInstances(mockedKubernetesClientFactory);
    when(mockedKubernetesClientFactory.kubernetes(any())).thenReturn(mockKubernetesClient);

    when(pods.inNamespace(Constants.KUBERNETES_NAMESPACE_KEY)).thenReturn(pods);

    when(pods.create(any())).thenAnswer(new Answer<Pod>() {
        @Override
        public Pod answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            return (Pod) args[0];
        }
    });

    when(pods.list()).thenReturn(new PodList());
    when(mockKubernetesClient.pods()).thenReturn(pods);

    createAgentRequest = CreateAgentRequestMother.defaultCreateAgentRequest();
    settings = PluginSettingsMother.defaultPluginSettings();
}
 
Example 8
Project: ditb   File: TestBulkLoad.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldBulkLoadManyFamilyHLogEvenWhenTableNameNamespaceSpecified() throws IOException {
  when(log.append(any(HTableDescriptor.class), any(HRegionInfo.class),
          any(WALKey.class), argThat(bulkLogWalEditType(WALEdit.BULK_LOAD)),
          any(boolean.class))).thenAnswer(new Answer() {
    public Object answer(InvocationOnMock invocation) {
      WALKey walKey = invocation.getArgumentAt(2, WALKey.class);
      MultiVersionConcurrencyControl mvcc = walKey.getMvcc();
      if (mvcc != null) {
        MultiVersionConcurrencyControl.WriteEntry we = mvcc.begin();
        walKey.setWriteEntry(we);
      }
      return 01L;
    };
  });
  TableName tableName = TableName.valueOf("test", "test");
  testRegionWithFamiliesAndSpecifiedTableName(tableName, family1, family2)
      .bulkLoadHFiles(withFamilyPathsFor(family1, family2), false, null);
  verify(log).sync(anyLong());
}
 
Example 9
Project: azure-documentdb-rxjava   File: SessionTest.java   Source Code and License 6 votes vote down vote up
private void setupSpySession(final List<String> capturedRequestSessionTokenList, final List<String> capturedResponseSessionTokenList, 
        RxDocumentClientImpl spyClient, final RxDocumentClientImpl origClient) throws DocumentClientException {

    Mockito.reset(spyClient);
    doAnswer(new Answer<Void>() {
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            RxDocumentServiceRequest req = (RxDocumentServiceRequest) args[0];
            DocumentServiceResponse resp = (DocumentServiceResponse) args[1];

            capturedRequestSessionTokenList.add(req.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN));
            capturedResponseSessionTokenList.add(resp.getResponseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN));

            origClient.captureSessionToken(req, resp);

            return null;
        }})
    .when(spyClient).captureSessionToken(Mockito.any(RxDocumentServiceRequest.class), Mockito.any(DocumentServiceResponse.class));
}
 
Example 10
Project: GitHub   File: GlideTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  Glide.tearDown();

  RobolectricPackageManager pm = RuntimeEnvironment.getRobolectricPackageManager();
  ApplicationInfo info =
      pm.getApplicationInfo(RuntimeEnvironment.application.getPackageName(), 0);
  info.metaData = new Bundle();
  info.metaData.putString(SetupModule.class.getName(), "GlideModule");

  // Ensure that target's size ready callback will be called synchronously.
  target = mock(Target.class);
  imageView = new ImageView(RuntimeEnvironment.application);
  imageView.setLayoutParams(new ViewGroup.LayoutParams(100, 100));
  imageView.layout(0, 0, 100, 100);
  doAnswer(new CallSizeReady()).when(target).getSize(isA(SizeReadyCallback.class));

  Handler bgHandler = mock(Handler.class);
  when(bgHandler.post(isA(Runnable.class))).thenAnswer(new Answer<Boolean>() {
    @Override
    public Boolean answer(InvocationOnMock invocation) throws Throwable {
      Runnable runnable = (Runnable) invocation.getArguments()[0];
      runnable.run();
      return true;
    }
  });

  Lifecycle lifecycle = mock(Lifecycle.class);
  RequestManagerTreeNode treeNode = mock(RequestManagerTreeNode.class);
  requestManager = new RequestManager(Glide.get(getContext()), lifecycle, treeNode);
  requestManager.resumeRequests();
}
 
Example 11
Project: empiria.player   File: PowerFeedbackMediatorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldNotifyClientsOnStateChanged_bothClients() {
    // given
    StateChangeEvent event = mockStateChangeEvent(true, false);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            EndHandler handler = (EndHandler) invocation.getArguments()[0];
            handler.onEnd();
            return null;
        }
    }).when(tutor).processUserInteraction(any(EndHandler.class));
    mediator.registerTutor(tutor);
    mediator.registerBonus(bonus);

    // when
    stateChangedHandler.onStateChange(event);

    // then
    InOrder inOrder = Mockito.inOrder(tutor, bonus);
    inOrder.verify(tutor).processUserInteraction(any(EndHandler.class));
    inOrder.verify(bonus).processUserInteraction();
}
 
Example 12
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: MQClientAPIImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSendMessageSync_Success() throws InterruptedException, RemotingException, MQBrokerException {
    doAnswer(new Answer() {
        @Override public Object answer(InvocationOnMock mock) throws Throwable {
            RemotingCommand request = mock.getArgument(1);
            return createSuccessResponse(request);
        }
    }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());

    SendMessageRequestHeader requestHeader = createSendMessageRequestHeader();

    SendResult sendResult = mqClientAPI.sendMessage(brokerAddr, brokerName, msg, requestHeader,
        3 * 1000, CommunicationMode.SYNC, new SendMessageContext(), defaultMQProducerImpl);

    assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
    assertThat(sendResult.getOffsetMsgId()).isEqualTo("123");
    assertThat(sendResult.getQueueOffset()).isEqualTo(123L);
    assertThat(sendResult.getMessageQueue().getQueueId()).isEqualTo(1);
}
 
Example 13
Project: rskj   File: BridgeSerializationUtilsTest.java   Source Code and License 6 votes vote down vote up
private void mock_RLP_decode2_forMapOfHashesToLong() {
    // Plain list with first elements being the size
    // Sizes are 1 byte long
    // e.g., for list [a,b,c] and a.size = 5, b.size = 7, c.size = 4, then:
    // 03050704[a bytes][b bytes][c bytes]
    when(RLP.decode2(any(byte[].class))).then((InvocationOnMock invocation) -> {
        RLPList result = new RLPList();
        byte[] arg = invocation.getArgumentAt(0, byte[].class);
        // Even byte -> hash of 64 bytes with same char from byte
        // Odd byte -> long from byte
        for (int i = 0; i < arg.length; i++) {
            byte[] element;
            if (i%2 == 0) {
                element = Hex.decode(charNTimes((char) arg[i], 64));
            } else {
                element = new byte[]{arg[i]};
            }
            result.add(() -> element);
        }
        return new ArrayList<>(Arrays.asList(result));
    });
}
 
Example 14
Project: empiria.player   File: ExplanationControllerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldCallPlayOrStopEntryOnPlayButtonClick() {
    // given
    String file = "test.mp3";
    Entry entry = mock(Entry.class);
    when(entry.getEntrySound()).thenReturn(file);

    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) {
            clickHandler = (ClickHandler) invocation.getArguments()[0];
            return null;
        }
    }).when(explanationView).addEntryPlayButtonHandler(any(ClickHandler.class));

    // when
    testObj.init();
    testObj.processEntry(entry);
    clickHandler.onClick(null);

    // then
    verify(entryDescriptionSoundController).playOrStopEntrySound(entry.getEntrySound());
}
 
Example 15
Project: osc-core   File: CheckK8sDeploymentStateTaskTest.java   Source Code and License 6 votes vote down vote up
private void registerAvailableKubernetesDeploymentAfterCount(DeploymentSpec ds, int count) throws VmidcException {
    KubernetesDeployment unavailableK8sDeployment = Mockito.mock(KubernetesDeployment.class);
    when(unavailableK8sDeployment.getAvailableReplicaCount())
    .thenReturn(ds.getInstanceCount() - 1);

    KubernetesDeployment availableK8sDeployment = Mockito.mock(KubernetesDeployment.class);
    when(availableK8sDeployment.getAvailableReplicaCount())
    .thenReturn(ds.getInstanceCount());

    when(this.k8sDeploymentApi
            .getDeploymentById(
                    ds.getExternalId(),
                    ds.getNamespace(),
                    K8sUtil.getK8sName(ds))).thenAnswer(new Answer<KubernetesDeployment>() {
                        private int i = 0;

                        @Override
                        public KubernetesDeployment answer(InvocationOnMock invocation) {
                            if (this.i++ == count) {
                                return availableK8sDeployment;
                            } else {
                                return unavailableK8sDeployment;
                            }
                        }
                    });
}
 
Example 16
Project: GitHub   File: EngineJobTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testNotifiesNewCallbackOfResourceIfCallbackIsAddedDuringOnResourceReady() {
  final EngineJob<Object> job = harness.getJob();
  final ResourceCallback existingCallback = mock(ResourceCallback.class);
  final ResourceCallback newCallback = mock(ResourceCallback.class);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      job.addCallback(newCallback);
      return null;
    }
  }).when(existingCallback).onResourceReady(anyResource(), isADataSource());

  job.addCallback(existingCallback);
  job.start(harness.decodeJob);
  job.onResourceReady(harness.resource, harness.dataSource);

  verify(newCallback).onResourceReady(eq(harness.engineResource), eq(harness.dataSource));
}
 
Example 17
Project: GitHub   File: EngineJobTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRemovingCallbackDuringOnExceptionIsIgnoredIfCallbackHasAlreadyBeenCalled() {
  harness = new EngineJobHarness();
  final EngineJob<Object> job = harness.getJob();
  final ResourceCallback cb = mock(ResourceCallback.class);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      job.removeCallback(cb);
      return null;
    }
  }).when(cb).onLoadFailed(any(GlideException.class));

  GlideException exception = new GlideException("test");
  job.addCallback(cb);
  job.start(harness.decodeJob);
  job.onLoadFailed(exception);

  verify(cb, times(1)).onLoadFailed(eq(exception));
}
 
Example 18
Project: GitHub   File: EngineJobTest.java   Source Code and License 6 votes vote down vote up
@Test
public void
testRemovingCallbackDuringOnResourceReadyPreventsResourceFromBeingAcquiredForCallback() {
  final EngineJob<Object> job = harness.getJob();
  final ResourceCallback notYetCalled = mock(ResourceCallback.class);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      job.removeCallback(notYetCalled);
      return null;
    }
  }).when(harness.cb).onResourceReady(anyResource(), isADataSource());

  job.addCallback(notYetCalled);
  job.start(harness.decodeJob);

  job.onResourceReady(harness.resource, harness.dataSource);

  // Once for notifying, once for called.
  verify(harness.engineResource, times(2)).acquire();
}
 
Example 19
Project: kotlin-late   File: LateTest.java   Source Code and License 6 votes vote down vote up
@Before
public void before() throws Exception {
    Answer<Cancelable> runAndReturn = new Answer<Cancelable>() {
        @Override
        public Cancelable answer(InvocationOnMock invocation) throws Exception {
            try {
                Function0<Unit> block = invocation.getArgument(0);
                block.invoke();
            } catch (Exception e) {
                e.printStackTrace();
                Assert.fail(e.getMessage());
            }
            return canceler;
        }
    };
    doAnswer(runAndReturn).when(mockRunner).runWithCancel(ArgumentMatchers.<Function0<Unit>>any());
    doAnswer(runAndReturn).when(mockRunner).run(ArgumentMatchers.<Function0<Unit>>any());
}
 
Example 20
Project: QuizZz   File: QuestionServiceTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testAddAnswerToQuestion_notFirstAnswer_shouldNotMarkItAsCorrect() {
	when(answerService.countAnswersInQuestion(question)).thenReturn(1);
	question.setIsValid(true);
	question.setCorrectAnswer(null);
	Answer answer = new Answer();
	answer.setId(1l);

	when(answerService.save(any(Answer.class))).thenAnswer(new org.mockito.stubbing.Answer<Answer>() {
		@Override
		public Answer answer(InvocationOnMock invocation) throws Throwable {
			Object[] args = invocation.getArguments();
			return (Answer) args[0];
		}
	});

	service.addAnswerToQuestion(answer, question);

	assertTrue(question.getIsValid());
	verify(answerService, times(1)).save(answer);
	verify(questionRepository, never()).save(question);
}
 
Example 21
Project: GitHub   File: ActivityMvpViewStateDelegateImplTestNew.java   Source Code and License 6 votes vote down vote up
@Test public void appStartAfterProcessDeathAndViewStateRecreationFromBundle() {
  ActivityMvpViewStateDelegateImpl<MvpView, MvpPresenter<MvpView>, ViewState<MvpView>> delegate =
      new ActivityMvpViewStateDelegateImpl<>(activity, callback, true);

  Mockito.doAnswer(new Answer() {
    @Override public Object answer(InvocationOnMock invocation) throws Throwable {
      viewState = Mockito.spy(new SimpleRestorableViewState());
      return viewState;
    }
  }).when(callback).createViewState();

  Bundle bundle = BundleMocker.create();
  bundle.putString(ActivityMvpViewStateDelegateImpl.KEY_MOSBY_VIEW_ID, "123456789");

  startActivity(delegate, bundle, 1, 1, 1, 1, 1, 1, false, 1, 0, 1);
}
 
Example 22
Project: hadoop   File: GenericTestUtils.java   Source Code and License 6 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
  boolean interrupted = false;
  try {
    Thread.sleep(r.nextInt(maxSleepTime));
  } catch (InterruptedException ie) {
    interrupted = true;
  }
  try {
    return invocation.callRealMethod();
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example 23
Project: server   File: AccountServiceTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	ledger = new Ledger();

	backlog = new Backlog();

	Storage mockStorage = mock(Storage.class);
	when(mockStorage.getBacklog()).thenReturn(backlog);
	service = Mockito.spy(new AccountService(mockStorage));
	doAnswer(new Answer<IAccount>() {
		@Override
		public IAccount answer(InvocationOnMock invocation) throws Throwable {
			long id = Format.ID.accountId(invocation.getArgument(0));
			return ledger.getAccount(id);
		}
	}).when(service).getAccount(anyString());

	Ed25519SignatureVerifier signatureVerifier = new Ed25519SignatureVerifier();
	CryptoProvider cryptoProvider = new CryptoProvider(new SignedObjectMapper(0L));
	cryptoProvider.addProvider(signatureVerifier);
	cryptoProvider.setDefaultProvider(signatureVerifier.getName());
	CryptoProvider.init(cryptoProvider);
}
 
Example 24
Project: spanner-jdbc   File: RunningOperationsStoreTest.java   Source Code and License 6 votes vote down vote up
private Operation<Void, UpdateDatabaseDdlMetadata> mockOperation(boolean error)
{
	@SuppressWarnings("unchecked")
	Operation<Void, UpdateDatabaseDdlMetadata> op = mock(Operation.class);
	when(op.getName()).then(new Returns("TEST_OPERATION"));
	when(op.isDone()).then(new Answer<Boolean>()
	{
		@Override
		public Boolean answer(InvocationOnMock invocation) throws Throwable
		{
			return reportDone;
		}
	});
	when(op.reload()).then(new Returns(op));
	if (error)
		when(op.getResult()).thenThrow(
				SpannerExceptionFactory.newSpannerException(ErrorCode.INVALID_ARGUMENT, "Some exception"));
	else
		when(op.getResult()).then(new Returns(null));
	UpdateDatabaseDdlMetadata metadata = UpdateDatabaseDdlMetadata.getDefaultInstance();
	when(op.getMetadata()).then(new Returns(metadata));

	return op;
}
 
Example 25
Project: alfresco-repository   File: ModuleServiceImplTest.java   Source Code and License 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) anyObject())).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) anyObject());
    doReturn(new Resource[] {simpleMod}).when(applicationContext).getResources(anyString());
    moduleService.setRegistryService(reg);
    moduleService.setApplicationContext(applicationContext);
}
 
Example 26
Project: es-log4j2-appender   File: ElasticSearchRestAppenderTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test that appender buffers events for 3 seconds before sending.
 *
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws InterruptedException the interrupted exception
 * @throws ExecutionException the execution exception
 */
@Test
public void test3sWait() throws IOException, InterruptedException, ExecutionException {
	BulkSender sender = Mockito.mock(BulkSender.class);
	ElasticSearchRestAppender appender = ElasticSearchRestAppender.newBuilder()
		.withName("test-3s-wait")
		.withBulkSender(sender)
		.withMaxBulkSize(0)
		.withMaxDelayTime(3000L)
		.build();
	verify(sender, times(0)).send(anyString());
	appender.append(getLogEvent());
	verify(sender, times(0)).send(anyString());
	CompletableFuture<Long> future = new CompletableFuture<>();
	long start = System.nanoTime();
	doAnswer(new Answer<Void>() {
		@Override
		public Void answer(InvocationOnMock invocation) throws Throwable {
			long elapsed = System.nanoTime() - start;
			future.complete(elapsed); 
			return null;
		}
	}).when(sender).send(anyString());
	assertTrue(future.get() >= 3000000);
	verify(sender, times(1)).send(anyString());
}
 
Example 27
Project: BitmapFontLoader   File: Bitmap3DStringTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetScaleMatrix() throws Exception {
    Bitmap3DString o = new Bitmap3DString(font, string);

    PowerMockito.doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            float[] matrix = (float[])args[0];
            for(int counter = 0; counter < matrix.length; counter++) {
                matrix[counter] = 2.0f;
            }
            return null;
        }
    }).when(Matrix.class, "scaleM", o.scaleMatrix, 0, o.getScaleX(), o.getScaleY(), o.getScaleZ());

    float[] expected = { 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f };
    assertArrayEquals(expected, o.getScaleMatrix(), 0);
}
 
Example 28
Project: oscm   File: RequestWithCleanParametersTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    loggerMock = mock(Log4jLogger.class);

    requestMock = mock(HttpServletRequest.class);
    map = new HashMap<String, String[]>();

    when(requestMock.getParameterMap()).thenReturn(map);
    when(requestMock.getRemoteAddr()).thenReturn(REMOTE_HOST);

    doAnswer(new Answer<String[]>() {
        @Override
        public String[] answer(InvocationOnMock invocation)
                throws Throwable {
            return map.get(invocation.getArguments()[0]);
        }
    }).when(requestMock).getParameterValues(anyString());

    when(requestMock.getQueryString()).thenReturn(queryString);

    RequestWithCleanParameters.logger = loggerMock;
}
 
Example 29
Project: filestack-java   File: TestClient.java   Source Code and License 6 votes vote down vote up
private static void setupUploadS3Mock(UploadService mockUploadService) {
  MediaType mediaType = MediaType.parse("text/xml");
  ResponseBody responseBody = ResponseBody.create(mediaType, "");
  final Response<ResponseBody> response = Response.success(responseBody,
      Headers.of("ETag", "test-etag"));
  Mockito
      .doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          return Calls.response(response);
        }
      })
      .when(mockUploadService)
      .uploadS3(Mockito.<String, String>anyMap(), Mockito.anyString(),
          Mockito.any(RequestBody.class));
}
 
Example 30
Project: oscm   File: UserGroupServiceLocalBeanTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = OperationNotPermittedException.class)
public void revokeUsersFromGroup_userNotBelongToOrg() throws Exception {
    // given
    group.setIsDefault(false);
    group.setOrganization(org);
    doReturn(platformUser).when(userGroupService.getDm()).find(
            any(PlatformUser.class));
    when(userGroupService.getDm().find(any(DomainObject.class)))
            .thenAnswer(new Answer<DomainObject<?>>() {

                @Override
                public DomainObject<?> answer(InvocationOnMock invocation) {
                    Object template = invocation.getArguments()[0];
                    if (template instanceof UserGroup) {
                        return group;
                    } else if (template instanceof PlatformUser) {
                        return platformUser;
                    }
                    return null;
                }
            });

    // when
    userGroupService.revokeUsersFromGroup(group,
            Collections.singletonList(user));
}
 
Example 31
Project: GitHub   File: EngineTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testHandlesNonEngineResourcesFromCacheIfPresent() {
  final Object expected = new Object();
  @SuppressWarnings("rawtypes") Resource fromCache = mockResource();
  when(fromCache.get()).thenReturn(expected);
  when(harness.cache.remove(eq(harness.cacheKey))).thenReturn(fromCache);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      Resource<?> resource = (Resource<?>) invocationOnMock.getArguments()[0];
      assertEquals(expected, resource.get());
      return null;
    }
  }).when(harness.cb).onResourceReady(anyResource(), isADataSource());

  harness.doLoad();

  verify(harness.cb).onResourceReady(anyResource(), isADataSource());
}
 
Example 32
Project: GitHub   File: EngineTest.java   Source Code and License 6 votes vote down vote up
@Test
public void load_afterResourceIsGcedFromActive_returnsFromMemoryCache() {
  when(harness.resource.getResource()).thenReturn(mock(Resource.class));
  when(harness.resource.isCacheable()).thenReturn(true);
  harness.cache = new LruResourceCache(100);
  doAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
      harness.getEngine().onEngineJobComplete(harness.cacheKey, harness.resource);
      return null;
    }
  }).when(harness.job).start(any(DecodeJob.class));
  harness.doLoad();
  ArgumentCaptor<IdleHandler> captor = ArgumentCaptor.forClass(IdleHandler.class);
  verify(GlideShadowLooper.queue).addIdleHandler(captor.capture());
  captor.getValue().queueIdle();
  harness.doLoad();
  verify(harness.cb).onResourceReady(any(Resource.class), eq(DataSource.MEMORY_CACHE));
}
 
Example 33
Project: ditb   File: TestBulkLoad.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldBulkLoadManyFamilyHLog() throws IOException {
  when(log.append(any(HTableDescriptor.class), any(HRegionInfo.class),
          any(WALKey.class), argThat(bulkLogWalEditType(WALEdit.BULK_LOAD)),
          any(boolean.class))).thenAnswer(new Answer() {
            public Object answer(InvocationOnMock invocation) {
              WALKey walKey = invocation.getArgumentAt(2, WALKey.class);
              MultiVersionConcurrencyControl mvcc = walKey.getMvcc();
              if (mvcc != null) {
                MultiVersionConcurrencyControl.WriteEntry we = mvcc.begin();
                walKey.setWriteEntry(we);
              }
              return 01L;
            };
          });
  testRegionWithFamilies(family1, family2).bulkLoadHFiles(withFamilyPathsFor(family1, family2),
          false, null);
  verify(log).sync(anyLong());
}
 
Example 34
Project: GitHub   File: EngineJobTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRemovingCallbackDuringOnResourceReadyIsIgnoredIfCallbackHasAlreadyBeenCalled() {
  final EngineJob<Object> job = harness.getJob();
  final ResourceCallback cb = mock(ResourceCallback.class);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      job.removeCallback(cb);
      return null;
    }
  }).when(cb).onResourceReady(anyResource(), isADataSource());

  job.addCallback(cb);
  job.start(harness.decodeJob);
  job.onResourceReady(harness.resource, harness.dataSource);

  verify(cb, times(1)).onResourceReady(anyResource(), isADataSource());
}
 
Example 35
Project: OCast-Java   File: SSDPDiscoveryTest.java   Source Code and License 6 votes vote down vote up
@Override
public DatagramSocket answer(InvocationOnMock invocation) throws Throwable {
    //if needed, the Socket can be retrieved with:
    //DatagramSocket socket = (DatagramSocket) invocation.getMock();
    int timeout = 5000;
    Object[] args = invocation.getArguments();
    if (mCount < mResponseToSend) {
        Thread.sleep(timeout/2);
        ((DatagramPacket) args[0]).setData(mAnswers[mCount].getBytes());
        mCount++;
        return null;
    } else {
        Thread.sleep(timeout);
        throw new InterruptedIOException();
    }
}
 
Example 36
Project: GitHub   File: EngineJobTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRemovingCallbackDuringOnExceptionPreventsCallbackFromBeingCalledIfNotYetCalled() {
  harness = new EngineJobHarness();
  final EngineJob<Object> job = harness.getJob();
  final ResourceCallback called = mock(ResourceCallback.class);
  final ResourceCallback notYetCalled = mock(ResourceCallback.class);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      job.removeCallback(notYetCalled);
      return null;
    }
  }).when(called).onLoadFailed(any(GlideException.class));

  job.addCallback(called);
  job.addCallback(notYetCalled);
  job.start(harness.decodeJob);
  job.onLoadFailed(new GlideException("test"));

  verify(notYetCalled, never()).onResourceReady(anyResource(), isADataSource());
}
 
Example 37
Project: monarch   File: BucketOperatorWrapperTest.java   Source Code and License 6 votes vote down vote up
@Test
public void bucketWrapperShouldInvokeOnFailureWhenCreateBucketFails() {
  doAnswer(new Answer<Object>() {
    public Object answer(InvocationOnMock invocation) {
      // 3rd argument is Completion object sent to BucketOperatorImpl.createRedundantBucket
      ((Completion) invocation.getArguments()[3]).onFailure();
      return null;
    }
  }).when(delegate).createRedundantBucket(eq(targetMember), eq(bucketId),
      eq(colocatedRegionBytes), any(Completion.class));

  Completion completionSentToWrapper = mock(Completion.class);
  wrapper.createRedundantBucket(targetMember, bucketId, colocatedRegionBytes,
      completionSentToWrapper);

  // verify onFailure is invoked
  verify(completionSentToWrapper, times(1)).onFailure();
}
 
Example 38
Project: filestack-java   File: TestFileLink.java   Source Code and License 6 votes vote down vote up
@Test
public void testImageSfw() throws Exception {
  Mockito.doAnswer(new Answer() {
    @Override
    public Call<ResponseBody> answer(InvocationOnMock invocation) throws Throwable {
      String handle = invocation.getArgument(1);
      String json = "{'sfw': " + (handle.equals("safe") ? "true" : "false") + "}";
      MediaType mediaType = MediaType.parse("application/json");
      return Calls.response(ResponseBody.create(mediaType, json));
    }
  })
      .when(Networking.getCdnService())
      .transform(Mockito.anyString(), Mockito.anyString());

  Config config = new Config("apiKey", "policy", "signature");

  FileLink safe = new FileLink(config, "safe");
  FileLink notSafe = new FileLink(config, "notSafe");

  Assert.assertTrue(safe.imageSfw());
  Assert.assertFalse(notSafe.imageSfw());
}
 
Example 39
Project: NoValid   File: StringUtilsTest.java   Source Code and License 5 votes vote down vote up
private void mockTextUtils() {
    mockStatic(TextUtils.class);
    PowerMockito.when(TextUtils.isEmpty(any(CharSequence.class))).thenAnswer(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            CharSequence a = (CharSequence) invocation.getArguments()[0];
            return !(a != null && a.length() > 0);
        }
    });
}
 
Example 40
Project: pcloud-networking-java   File: RealMultiCallTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSuccessfulEnqueueReportsResultsToTheCallback() throws Exception {
    List<Request> requestList = getMockRequestList(Endpoint.DEFAULT, 3);
    final Connection connection = createDummyConnection(Endpoint.DEFAULT, getMockByteDataResponse(requestList.size()));
    retrofitConnectionProvider(connection);

    final MultiCall call = createMultiCall(requestList, executor);

    when(executor.submit(any(Runnable.class))).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            Runnable runnable = ((Runnable) args[0]);
            runnable.run();
            return new FutureTask<Void>(runnable, null);
        }
    });
    MultiCallback callback = mock(MultiCallback.class);

    call.enqueue(callback);

    ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class);

    verify(callback).onComplete(eq(call), notNull(MultiResponse.class));
    verify(connectionProvider).recycleConnection(connection);
    verify(callback, times(call.requests().size())).onResponse(eq(call), captor.capture(), any(Response.class));

    List<Integer> values = captor.getAllValues();
    for (int i = 0; i < values.size(); i++) {
        assertTrue(values.contains(i));
    }
}
 
Example 41
Project: GitHub   File: HttpUrlConnectionNetworkFetcherTest.java   Source Code and License 5 votes vote down vote up
private void mockFetchState() {
  when(mMockFetchState.getContext()).thenReturn(mMockProducerContext);
  when(mMockFetchState.getUri()).then(new Answer<Uri>() {
    @Override
    public Uri answer(InvocationOnMock invocation) throws Throwable {
      return mockUri(INITIAL_TEST_URL);
    }
  });
}
 
Example 42
Project: RNLearn_Project1   File: NetworkingModuleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testHeaders() throws Exception {
  OkHttpClient httpClient = mock(OkHttpClient.class);
  when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      Call callMock = mock(Call.class);
      return callMock;
    }
  });
  OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class);
  when(clientBuilder.build()).thenReturn(httpClient);
  when(httpClient.newBuilder()).thenReturn(clientBuilder);
  NetworkingModule networkingModule =
    new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient);

  List<JavaOnlyArray> headers = Arrays.asList(
      JavaOnlyArray.of("Accept", "text/plain"),
      JavaOnlyArray.of("User-Agent", "React test agent/1.0"));

  networkingModule.sendRequest(
    mock(ExecutorToken.class),
    "GET",
    "http://someurl/baz",
    0,
    JavaOnlyArray.from(headers),
    null,
    /* responseType */ "text",
    /* useIncrementalUpdates*/ true,
    /* timeout */ 0);
  ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
  verify(httpClient).newCall(argumentCaptor.capture());
  Headers requestHeaders = argumentCaptor.getValue().headers();
  assertThat(requestHeaders.size()).isEqualTo(2);
  assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain");
  assertThat(requestHeaders.get("User-Agent")).isEqualTo("React test agent/1.0");
}
 
Example 43
Project: GitHub   File: DataSourceTestUtils.java   Source Code and License 5 votes vote down vote up
/** Schedule response on subscribe. */
protected static <T> void respondOnSubscribe(
    final DataSource<T> dataSource,
    final int response) {
  doAnswer(
      new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          DataSubscriber<T> subscriber = (DataSubscriber<T>) invocation.getArguments()[0];
          respond(subscriber, dataSource, response);
          return subscriber;
        }
      }).when(dataSource).subscribe(any(DataSubscriber.class), any(Executor.class));
}
 
Example 44
Project: GitHub   File: HttpUrlConnectionNetworkFetcherTest.java   Source Code and License 5 votes vote down vote up
private void mockUrlConnections() throws Exception {
  URL mockUrl = PowerMockito.mock(URL.class);
  PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockUrl);

  PowerMockito.when(mockUrl.openConnection()).then(new Answer<URLConnection>() {
    @Override
    public URLConnection answer(InvocationOnMock invocation) throws Throwable {
      return mConnectionsQueue.poll();
    }
  });
}
 
Example 45
Project: ditb   File: TestSimpleRpcScheduler.java   Source Code and License 5 votes vote down vote up
private void doAnswerTaskExecution(final CallRunner callTask,
    final ArrayList<Integer> results, final int value, final int sleepInterval) {
  callTask.setStatus(new MonitoredRPCHandlerImpl());
  doAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) {
      synchronized (results) {
        results.add(value);
      }
      Threads.sleepWithoutInterrupt(sleepInterval);
      return null;
    }
  }).when(callTask).run();
}
 
Example 46
Project: GitHub   File: RequestFutureTargetTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = InterruptedException.class)
public void testThrowsInterruptedExceptionIfThreadInterruptedWhenDoneWaiting()
    throws InterruptedException, ExecutionException {
  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      Thread.currentThread().interrupt();
      return null;
    }
  }).when(waiter).waitForTimeout(eq(future), anyLong());

  future.get();
}
 
Example 47
Project: GitHub   File: RequestFutureTargetTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = ExecutionException.class)
public void testThrowsExecutionExceptionIfLoadFailsWhileWaiting()
    throws ExecutionException, InterruptedException {
  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      future.onLoadFailed(null);
      return null;
    }
  }).when(waiter).waitForTimeout(eq(future), anyLong());
  future.get();
}
 
Example 48
Project: GitHub   File: RequestFutureTargetTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = CancellationException.class)
public void testThrowsCancellationExceptionIfCancelledWhileWaiting()
    throws ExecutionException, InterruptedException {
  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      future.cancel(false);
      return null;
    }
  }).when(waiter).waitForTimeout(eq(future), anyLong());
  future.get();
}
 
Example 49
Project: ditb   File: TestProcedureMember.java   Source Code and License 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(timeout = 60000)
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(Exception.class));
  order.verify(spySub).cleanup(any(Exception.class));
}
 
Example 50
Project: KBUnitTest   File: JRAnswer.java   Source Code and License 5 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
    Object[] arguments  = invocation.getArguments();
    Method   method     = invocation.getMethod();
    Class[]  paramTypes = method.getParameterTypes();

    // 找到resource一模一样的方法
    Method method2 = ReflectUtils.findMethod(realObject.getClass(), method.getName(), paramTypes);

    return method2.invoke(realObject, arguments);
}
 
Example 51
Project: hadoop   File: TestAuthenticationFilter.java   Source Code and License 5 votes vote down vote up
private static void verifyUnauthorized(AuthenticationFilter filter,
                                       HttpServletRequest request,
                                       HttpServletResponse response,
                                       FilterChain chain) throws
                                                          IOException,
                                                          ServletException {
  final HashMap<String, String> cookieMap = new HashMap<String, String>();
  Mockito.doAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      String cookieHeader = (String) invocation.getArguments()[1];
      parseCookieMap(cookieHeader, cookieMap);
      return null;
    }
  }).when(response).addHeader(Mockito.eq("Set-Cookie"), Mockito.anyString());

  filter.doFilter(request, response, chain);

  Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse
          .SC_UNAUTHORIZED), Mockito.anyString());
  Mockito.verify(chain, Mockito.never()).doFilter(Mockito.any
          (ServletRequest.class), Mockito.any(ServletResponse.class));

  Assert.assertTrue("cookie is missing",
      cookieMap.containsKey(AuthenticatedURL.AUTH_COOKIE));
  Assert.assertEquals("", cookieMap.get(AuthenticatedURL.AUTH_COOKIE));
}
 
Example 52
Project: oscm   File: PartnerRevenueBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void processService_createRevenueDetailService() throws Exception {
    // given
    PartnerRevenueBuilder builder = spy(new PartnerRevenueBuilder(
            Locale.ENGLISH, null));

    doReturn("1").when(builder).readServiceRevenue(anyString(),
            anyString(), anyString());
    doReturn("423").when(builder).getServiceKey(any(Node.class));

    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            return null;
        }
    }).when(builder).createRevenueDetailService(anyInt(), anyString(),
            anyString(), anyString());

    List<RDORevenueDetailService> result = new LinkedList<RDORevenueDetailService>();
    Node dummyService = null;

    // when
    builder.processService(result, 0, dummyService, "dummy", "dummy");

    // then
    assertEquals(1, result.size());
    verify(builder, times(1)).createRevenueDetailService(anyInt(),
            anyString(), anyString(), anyString());
}
 
Example 53
Project: metanome-algorithms   File: ConditionalUniqueAndOrFixture.java   Source Code and License 5 votes vote down vote up
public RelationalInputGenerator getInputGenerator()
        throws InputGenerationException, InputIterationException, AlgorithmConfigurationException {
  RelationalInputGenerator inputGenerator = mock(RelationalInputGenerator.class);
  this.input = this.getRelationalInput();
  when(inputGenerator.generateNewCopy())
      .thenAnswer(new Answer<RelationalInput>() {
        public RelationalInput answer(InvocationOnMock invocation) throws Throwable {
          rowPosition = 0;
          return input;
        }
      });
  return inputGenerator;
}
 
Example 54
Project: alfresco-repository   File: WorklfowObjectFactoryTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test to validate ALF-18332 (default description label key).
 */
public void testTransitionDefaultLabel()
{
    MessageService mockedMessageService = Mockito.mock(MessageService.class);
    Mockito.when(mockedMessageService.getMessage(Mockito.anyString())).thenAnswer(new Answer<String>()
    {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable
        {
            String arg = (String) invocation.getArguments()[0];
            if ("base.key.title".equals(arg))
            {
                return "The title";
            }
            else if ("base.key.description".equals(arg))
            {
                return "The description";
            }
            return null;
        }
    });

    WorkflowObjectFactory factory = new WorkflowObjectFactory(null, null, mockedMessageService, null, ActivitiConstants.ENGINE_ID, null);
    WorkflowTransition createTransition = factory.createTransition("test-transition", "title", null, true, "base.key");
    assertNotNull(createTransition);
    assertEquals("The title", createTransition.getTitle());
    assertEquals("The description", createTransition.getDescription());
}
 
Example 55
Project: hadoop   File: TestDelegationTokenRenewer.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testAddRemoveRenewAction() throws IOException,
    InterruptedException {
  Text service = new Text("myservice");
  Configuration conf = mock(Configuration.class);

  Token<?> token = mock(Token.class);
  doReturn(service).when(token).getService();
  doAnswer(new Answer<Long>() {
    public Long answer(InvocationOnMock invocation) {
      return Time.now() + RENEW_CYCLE;
    }
  }).when(token).renew(any(Configuration.class));

  RenewableFileSystem fs = mock(RenewableFileSystem.class);
  doReturn(conf).when(fs).getConf();
  doReturn(token).when(fs).getRenewToken();

  renewer.addRenewAction(fs);
  
  assertEquals("FileSystem not added to DelegationTokenRenewer", 1,
      renewer.getRenewQueueLength());
  
  Thread.sleep(RENEW_CYCLE*2);
  verify(token, atLeast(2)).renew(eq(conf));
  verify(token, atMost(3)).renew(eq(conf));
  verify(token, never()).cancel(any(Configuration.class));
  renewer.removeRenewAction(fs);
  verify(token).cancel(eq(conf));

  verify(fs, never()).getDelegationToken(null);
  verify(fs, never()).setDelegationToken(any(Token.class));
  
  assertEquals("FileSystem not removed from DelegationTokenRenewer", 0,
      renewer.getRenewQueueLength());
}
 
Example 56
Project: ditb   File: TestBulkLoad.java   Source Code and License 5 votes vote down vote up
@Test
public void verifyBulkLoadEvent() throws IOException {
  TableName tableName = TableName.valueOf("test", "test");
  List<Pair<byte[], String>> familyPaths = withFamilyPathsFor(family1);
  byte[] familyName = familyPaths.get(0).getFirst();
  String storeFileName = familyPaths.get(0).getSecond();
  storeFileName = (new Path(storeFileName)).getName();
  List<String> storeFileNames = new ArrayList<String>();
  storeFileNames.add(storeFileName);
  when(log.append(any(HTableDescriptor.class), any(HRegionInfo.class), any(WALKey.class),
          argThat(bulkLogWalEdit(WALEdit.BULK_LOAD, tableName.toBytes(),
                  familyName, storeFileNames)),
          any(boolean.class))).thenAnswer(new Answer() {
    public Object answer(InvocationOnMock invocation) {
      WALKey walKey = invocation.getArgumentAt(2, WALKey.class);
      MultiVersionConcurrencyControl mvcc = walKey.getMvcc();
      if (mvcc != null) {
        MultiVersionConcurrencyControl.WriteEntry we = mvcc.begin();
        walKey.setWriteEntry(we);
      }
      return 01L;
    };
  });
  testRegionWithFamiliesAndSpecifiedTableName(tableName, family1)
      .bulkLoadHFiles(familyPaths, false, null);
  verify(log).sync(anyLong());
}
 
Example 57
Project: GitHub   File: Util.java   Source Code and License 5 votes vote down vote up
public Object answer(InvocationOnMock invocation) throws Throwable {
  Object mock = invocation.getMock();
  if (invocation.getMethod().getReturnType().isInstance(mock)) {
    return mock;
  } else {
    return RETURNS_DEFAULTS.answer(invocation);
  }
}
 
Example 58
Project: YuiHatano   File: JRAnswer.java   Source Code and License 5 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
    Object[] arguments  = invocation.getArguments();
    Method   method     = invocation.getMethod();
    Class[]  paramTypes = method.getParameterTypes();

    // 找到resource一模一样的方法
    Method method2 = ReflectUtils.findMethod(realObject.getClass(), method.getName(), paramTypes);

    return method2.invoke(realObject, arguments);
}
 
Example 59
Project: oscm   File: ServiceProvisioningServiceBeanTriggerIdIT.java   Source Code and License 5 votes vote down vote up
@Override
protected void setup(TestContainer container) throws Exception {
    container.enableInterfaceMocking(true);

    TriggerQueueServiceLocal triggerQueueServiceLocal = mock(
            TriggerQueueServiceLocal.class);
    container.addBean(triggerQueueServiceLocal);
    container.addBean(new ConfigurationServiceStub());
    container.addBean(new DataServiceBean());
    container.addBean(new ServiceProvisioningServiceBean());

    svcProv = container.get(ServiceProvisioningService.class);
    mgr = container.get(DataService.class);

    // Initialize the test setup data.
    initData();

    // mock the answer of the trigger queue
    doAnswer(new Answer<List<TriggerProcessMessageData>>() {
        @Override
        public List<TriggerProcessMessageData> answer(
                InvocationOnMock invocation) throws Throwable {
            return Collections.singletonList(triggerProcessData);
        }
    }).when(triggerQueueServiceLocal)
            .sendSuspendingMessages(anyListOf(TriggerMessage.class));

}
 
Example 60
Project: GitHub   File: AbstractPresenterDestroyTest.java   Source Code and License 5 votes vote down vote up
@NonNull
private Answer getFromMap(final HashMap<String, String> store) {
    return new Answer() {
        @Override
        public String answer(final InvocationOnMock invocation) throws Throwable {
            final Object[] args = invocation.getArguments();
            //noinspection RedundantCast
            return store.get((String) args[0]);
        }
    };
}