当前位置: 首页>>代码示例>>Java>>正文


Java InvocationOnMock类代码示例

本文整理汇总了Java中org.mockito.invocation.InvocationOnMock的典型用法代码示例。如果您正苦于以下问题:Java InvocationOnMock类的具体用法?Java InvocationOnMock怎么用?Java InvocationOnMock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


InvocationOnMock类属于org.mockito.invocation包,在下文中一共展示了InvocationOnMock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createOkResponseWithCookie

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
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;
        }
    };
}
 
开发者ID:philipwhiuk,项目名称:q-mail,代码行数:17,代码来源:WebDavStoreTest.java

示例2: testSendMessageSync_Success

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
@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);
}
 
开发者ID:lirenzuo,项目名称:rocketmq-rocketmq-all-4.1.0-incubating,代码行数:20,代码来源:MQClientAPIImplTest.java

示例3: answer

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
@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();
}
 
开发者ID:naver,项目名称:hadoop,代码行数:23,代码来源:TestBlockToken.java

示例4: testSuccessfulEnqueueReportsResultToTheCallback

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
@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));
}
 
开发者ID:pCloud,项目名称:pcloud-networking-java,代码行数:26,代码来源:RealCallTest.java

示例5: respondToFetchEnvelopesWithMessage

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
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));
}
 
开发者ID:philipwhiuk,项目名称:q-mail,代码行数:18,代码来源:MessagingControllerTest.java

示例6: initEventHandlersInterception

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
@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));
}
 
开发者ID:YoungDigitalPlanet,项目名称:empiria.player,代码行数:26,代码来源:PowerFeedbackMediatorTest.java

示例7: testAddAnswerToQuestion_firstAnswer_shouldEnableQuestionAndMarkItAsCorrect

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
@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);
}
 
开发者ID:oojorgeoo89,项目名称:QuizZz,代码行数:24,代码来源:QuestionServiceTests.java

示例8: setUp

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
@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();
}
 
开发者ID:gocd,项目名称:kubernetes-elastic-agents,代码行数:23,代码来源:KubernetesAgentInstancesIntegrationTest.java

示例9: shouldBulkLoadManyFamilyHLogEvenWhenTableNameNamespaceSpecified

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
@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());
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:21,代码来源:TestBulkLoad.java

示例10: setupSpySession

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
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));
}
 
开发者ID:Azure,项目名称:azure-documentdb-rxjava,代码行数:20,代码来源:SessionTest.java

示例11: setUp

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
@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();
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:33,代码来源:GlideTest.java

示例12: shouldNotifyClientsOnStateChanged_bothClients

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
@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();
}
 
开发者ID:YoungDigitalPlanet,项目名称:empiria.player,代码行数:25,代码来源:PowerFeedbackMediatorTest.java

示例13: mock_RLP_decode2_forMapOfHashesToLong

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
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));
    });
}
 
开发者ID:rsksmart,项目名称:rskj,代码行数:23,代码来源:BridgeSerializationUtilsTest.java

示例14: shouldCallPlayOrStopEntryOnPlayButtonClick

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
@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());
}
 
开发者ID:YoungDigitalPlanet,项目名称:empiria.player,代码行数:24,代码来源:ExplanationControllerTest.java

示例15: registerAvailableKubernetesDeploymentAfterCount

import org.mockito.invocation.InvocationOnMock; //导入依赖的package包/类
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;
                            }
                        }
                    });
}
 
开发者ID:opensecuritycontroller,项目名称:osc-core,代码行数:27,代码来源:CheckK8sDeploymentStateTaskTest.java


注:本文中的org.mockito.invocation.InvocationOnMock类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。