类org.mockito.stubbing.OngoingStubbing源码实例Demo

下面列出了怎么用org.mockito.stubbing.OngoingStubbing的API类实例代码及写法,或者点击链接到github查看源代码。

private OngoingStubbing<Call> mockReturnDocument(OngoingStubbing<Call> stub,
        final String document, int statusCode, String statusMessage) {
    return stub.thenAnswer(new Answer<Call>() {

        @Override
        public Call answer(InvocationOnMock invocationOnMock) throws Throwable {
            Request realRequest = (Request) invocationOnMock.getArguments()[0];
            Response mockResponse = new Response.Builder()
                    .request(realRequest)
                    .protocol(Protocol.HTTP_1_1)
                    .code(statusCode)
                    .message(statusMessage)
                    .body(ResponseBody.create(MediaType.parse("application/json"), document))
                    .build();
            final Call call = mock(Call.class);
            if (exceptionToThrow != null) {
                when(call.execute()).thenThrow(exceptionToThrow);
            } else {
                when(call.execute()).thenReturn(mockResponse);
            }
            return call;
        }
    });
}
 
源代码2 项目: javaide   文件: PrivateResourceDetectorTest.java
public static AndroidLibrary createMockLibrary(String allResources, String publicResources,
        List<AndroidLibrary> dependencies)
        throws IOException {
    final File tempDir = TestUtils.createTempDirDeletedOnExit();

    Files.write(allResources, new File(tempDir, FN_RESOURCE_TEXT), Charsets.UTF_8);
    File publicTxtFile = new File(tempDir, FN_PUBLIC_TXT);
    if (publicResources != null) {
        Files.write(publicResources, publicTxtFile, Charsets.UTF_8);
    }
    AndroidLibrary library = mock(AndroidLibrary.class);
    when(library.getPublicResources()).thenReturn(publicTxtFile);

    // Work around wildcard capture
    //when(mock.getLibraryDependencies()).thenReturn(dependencies);
    List libraryDependencies = library.getLibraryDependencies();
    OngoingStubbing<List> setter = when(libraryDependencies);
    setter.thenReturn(dependencies);
    return library;
}
 
源代码3 项目: titus-control-plane   文件: LoadBalancerTests.java
/**
 * Configures a V3 mock to return job from getJobs() that passes validation.
 */
static OngoingStubbing<?> applyValidGetJobMock(V3JobOperations mockedV3Ops, String jobId) {
    return when(mockedV3Ops.getJob(jobId)).thenReturn(Optional.of(Job.<ServiceJobExt>newBuilder()
            .withId(jobId)
            .withStatus(JobStatus.newBuilder()
                    .withState(JobState.Accepted)
                    .build())
            .withJobDescriptor(JobDescriptor.<ServiceJobExt>newBuilder()
                    .withExtensions(ServiceJobExt.newBuilder().build())
                    .withContainer(Container.newBuilder()
                            .withImage(Image.newBuilder().build())
                            .withContainerResources(ContainerResources.newBuilder()
                                    .withAllocateIP(true)
                                    .build())
                            .build())
                    .build())
            .build()));
}
 
源代码4 项目: nifi   文件: TestQueryElasticsearchHttp.java
private OngoingStubbing<Call> mockReturnDocument(OngoingStubbing<Call> stub,
        final String document, int statusCode, String statusMessage) {
    return stub.thenAnswer(new Answer<Call>() {

        @Override
        public Call answer(InvocationOnMock invocationOnMock) throws Throwable {
            Request realRequest = (Request) invocationOnMock.getArguments()[0];
            assertTrue((expectedParam == null) || (realRequest.url().toString().endsWith(expectedParam)));
            Response mockResponse = new Response.Builder()
                    .request(realRequest)
                    .protocol(Protocol.HTTP_1_1)
                    .code(statusCode)
                    .message(statusMessage)
                    .body(ResponseBody.create(MediaType.parse("application/json"), document))
                    .build();
            final Call call = mock(Call.class);
            if (exceptionToThrow != null) {
                when(call.execute()).thenThrow(exceptionToThrow);
            } else {
                when(call.execute()).thenReturn(mockResponse);
            }
            return call;
        }
    });
}
 
@Test
public void second_stubbing_throws_IndexOutOfBoundsException() throws Exception {
    Map<String, String> map = mock(Map.class);

    OngoingStubbing<String> mapOngoingStubbing = when(map.get(anyString()));

    mapOngoingStubbing.thenReturn("first stubbing");

    try {
        mapOngoingStubbing.thenReturn("second stubbing");
        fail();
    } catch (MockitoException e) {
        assertThat(e.getMessage())
                .contains("Incorrect use of API detected here")
                .contains(this.getClass().getSimpleName());
    }
}
 
源代码6 项目: sqoop-on-spark   文件: TestKiteExtractor.java
@Test
public void testExtractor() throws Exception {
  // setup
  Schema schema = new Schema("testExtractor");
  schema.addColumn(new Text("TextCol"));
  ExtractorContext context = new ExtractorContext(null, writerMock, schema);
  LinkConfiguration linkConfig = new LinkConfiguration();
  FromJobConfiguration jobConfig = new FromJobConfiguration();
  KiteDatasetPartition partition = new KiteDatasetPartition();
  partition.setUri("dataset:hdfs:/path/to/dataset");
  OngoingStubbing<Object[]> readRecordMethodStub = when(executorMock.readRecord());
  final int NUMBER_OF_ROWS = 1000;
  for (int i = 0; i < NUMBER_OF_ROWS; i++) {
    // TODO: SQOOP-1616 will cover more column data types
    readRecordMethodStub = readRecordMethodStub.thenReturn(new Object[]{});
  }
  readRecordMethodStub.thenReturn(null);

  // exercise
  extractor.extract(context, linkConfig, jobConfig, partition);

  // verify
  verify(writerMock, times(NUMBER_OF_ROWS)).writeArrayRecord(
      any(Object[].class));
}
 
private void getAllPrBuildsCommonExpectations(int size) {
    when(job.getBuilds()).thenReturn(builds);
    when(builds.size()).thenReturn(size);
    when(job.getParent()).thenReturn(itemGroup);
    when(itemGroup.getFullName()).thenReturn("JobName");

    when(builds.iterator()).thenReturn(iterator);

    OngoingStubbing<Boolean> hasNextExpectation = size >= 1 ?
            when(iterator.hasNext()).thenReturn(true) : when(iterator.hasNext()).thenReturn(false);
    for (int i = 1; i < size; i++) {
        hasNextExpectation.thenReturn(true);
    }
    hasNextExpectation.thenReturn(false);

    OngoingStubbing<Object> nextExpectation = when(iterator.next()).thenReturn(run);
    for (int i = 1; i < size; i++) {
        nextExpectation.thenReturn(run);
    }
}
 
源代码8 项目: codenjoy   文件: SpaceraceTest.java
private void diceNew(int...ints) {
    OngoingStubbing<Integer> when = when(dice.next(anyInt()));

    if(ints.length == 0){ // we work just with nothing
        when = when.thenReturn(-1);
    }

    if(ints.length == 1){ // we work just with stones
        when = when.thenReturn(-1, -1, -1, -1, ints[0], -1);
    }

    if(ints.length == 2){ // we work with stones and bombs
        when = when.thenReturn(-1, -1, -1, -1, ints[0], ints[1], -1);
    }

    if(ints.length == 4){ // we work stones, bombs and bulletPacks
        when = when.thenReturn(ints[2], ints[3], ints[0], ints[1], -1);
    }
}
 
private void mockBytes(int... bytes) {
  when(buffer.readableBytes()).thenReturn(bytes.length);
  OngoingStubbing<Integer> stub = when(buffer.readUnsignedByte());
  for (int b : bytes) {
    stub = stub.thenReturn(b);
  }
}
 
源代码10 项目: client-sdk-java   文件: JsonRpc2_0RxTest.java
@Test
public void testReplayBlocksObservable() throws Exception {

    List<PlatonBlock> ethBlocks = Arrays.asList(createBlock(0), createBlock(1), createBlock(2));

    OngoingStubbing<PlatonBlock> stubbing =
            when(web3jService.send(any(Request.class), eq(PlatonBlock.class)));
    for (PlatonBlock ethBlock : ethBlocks) {
        stubbing = stubbing.thenReturn(ethBlock);
    }

    Observable<PlatonBlock> observable = web3j.replayBlocksObservable(
            new DefaultBlockParameterNumber(BigInteger.ZERO),
            new DefaultBlockParameterNumber(BigInteger.valueOf(2)),
            false);

    CountDownLatch transactionLatch = new CountDownLatch(ethBlocks.size());
    CountDownLatch completedLatch = new CountDownLatch(1);

    List<PlatonBlock> results = new ArrayList<>(ethBlocks.size());
    Subscription subscription = observable.subscribe(
            result -> {
                results.add(result);
                transactionLatch.countDown();
            },
            throwable -> fail(throwable.getMessage()),
            () -> completedLatch.countDown());

    transactionLatch.await(1, TimeUnit.SECONDS);
    assertThat(results, equalTo(ethBlocks));

    subscription.unsubscribe();

    completedLatch.await(1, TimeUnit.SECONDS);
    assertTrue(subscription.isUnsubscribed());
}
 
源代码11 项目: client-sdk-java   文件: JsonRpc2_0RxTest.java
@Test
public void testReplayBlocksDescendingObservable() throws Exception {

    List<PlatonBlock> ethBlocks = Arrays.asList(createBlock(2), createBlock(1), createBlock(0));

    OngoingStubbing<PlatonBlock> stubbing =
            when(web3jService.send(any(Request.class), eq(PlatonBlock.class)));
    for (PlatonBlock ethBlock : ethBlocks) {
        stubbing = stubbing.thenReturn(ethBlock);
    }

    Observable<PlatonBlock> observable = web3j.replayBlocksObservable(
            new DefaultBlockParameterNumber(BigInteger.ZERO),
            new DefaultBlockParameterNumber(BigInteger.valueOf(2)),
            false, false);

    CountDownLatch transactionLatch = new CountDownLatch(ethBlocks.size());
    CountDownLatch completedLatch = new CountDownLatch(1);

    List<PlatonBlock> results = new ArrayList<>(ethBlocks.size());
    Subscription subscription = observable.subscribe(
            result -> {
                results.add(result);
                transactionLatch.countDown();
            },
            throwable -> fail(throwable.getMessage()),
            () -> completedLatch.countDown());

    transactionLatch.await(1, TimeUnit.SECONDS);
    assertThat(results, equalTo(ethBlocks));

    subscription.unsubscribe();

    completedLatch.await(1, TimeUnit.SECONDS);
    assertTrue(subscription.isUnsubscribed());
}
 
源代码12 项目: salt-step   文件: RetryingHttpClientExecutorTest.java
protected void setupResponseWithStatusLine(int... codes) {
    StatusLine line = Mockito.mock(StatusLine.class);
    OngoingStubbing<Integer> stub = Mockito.when(line.getStatusCode());
    for (int code : codes) {
        stub = stub.thenReturn(code);
    }
    Mockito.when(response.getStatusLine()).thenReturn(line);
}
 
源代码13 项目: etherscan-explorer   文件: JsonRpc2_0RxTest.java
@Test
public void testReplayBlocksDescendingObservable() throws Exception {

    List<EthBlock> ethBlocks = Arrays.asList(createBlock(2), createBlock(1), createBlock(0));

    OngoingStubbing<EthBlock> stubbing =
            when(web3jService.send(any(Request.class), eq(EthBlock.class)));
    for (EthBlock ethBlock : ethBlocks) {
        stubbing = stubbing.thenReturn(ethBlock);
    }

    Observable<EthBlock> observable = web3j.replayBlocksObservable(
            new DefaultBlockParameterNumber(BigInteger.ZERO),
            new DefaultBlockParameterNumber(BigInteger.valueOf(2)),
            false, false);

    CountDownLatch transactionLatch = new CountDownLatch(ethBlocks.size());
    CountDownLatch completedLatch = new CountDownLatch(1);

    List<EthBlock> results = new ArrayList<>(ethBlocks.size());
    Subscription subscription = observable.subscribe(
            result -> {
                results.add(result);
                transactionLatch.countDown();
            },
            throwable -> fail(throwable.getMessage()),
            () -> completedLatch.countDown());

    transactionLatch.await(1, TimeUnit.SECONDS);
    assertThat(results, equalTo(ethBlocks));

    subscription.unsubscribe();

    completedLatch.await(1, TimeUnit.SECONDS);
    assertTrue(subscription.isUnsubscribed());
}
 
@Override
protected void createElasticsearchClient(ProcessContext context) throws ProcessException {
    client = mock(OkHttpClient.class);

    OngoingStubbing<Call> stub = when(client.newCall(any(Request.class)));

    for (int i = 0; i < pages.size(); i++) {
        String page = pages.get(i);
        if (runNumber == i + 1) {
            stub = mockReturnDocument(stub, page, badStatusCode, badStatusMessage);
        } else {
            stub = mockReturnDocument(stub, page, goodStatusCode, goodStatusMessage);
        }
    }
}
 
@Override
protected void createElasticsearchClient(ProcessContext context) throws ProcessException {
    client = mock(OkHttpClient.class);

    OngoingStubbing<Call> stub = when(client.newCall(any(Request.class)));

    for (int i = 0; i < pages.size(); i++) {
        String page = pages.get(i);
        if (runNumber == i + 1) {
            stub = mockReturnDocument(stub, page, badStatusCode, badStatusMessage);
        } else {
            stub = mockReturnDocument(stub, page, goodStatusCode, goodStatusMessage);
        }
    }
}
 
源代码16 项目: elasticsearch-hadoop   文件: BulkProcessorTest.java
private RestClient mockClientResponses(RestClient.BulkActionResponse... responses) {
    RestClient mockClient = Mockito.mock(RestClient.class);

    OngoingStubbing<RestClient.BulkActionResponse> stubb = Mockito.when(
            mockClient.bulk(Mockito.eq(resource), Mockito.any(TrackingBytesArray.class))
    );

    for (RestClient.BulkActionResponse response : responses) {
        stubb = stubb.thenReturn(response);
    }

    stubb.thenThrow(new AssertionError("Exhausted all given test responses."));

    return mockClient;
}
 
源代码17 项目: codenjoy   文件: SingleTest.java
private Dice givenDice(int... values) {
    Dice dice1 = mock(Dice.class);
    OngoingStubbing<Integer> when = when(dice1.next(anyInt()));
    for (int value : values) {
        when = when.thenReturn(value);
    }
    return dice1;
}
 
源代码18 项目: nifi   文件: TestQueryElasticsearchHttp.java
@Override
protected void createElasticsearchClient(ProcessContext context) throws ProcessException {
    client = mock(OkHttpClient.class);

    OngoingStubbing<Call> stub = when(client.newCall(any(Request.class)));

    for (int i = 0; i < pages.size(); i++) {
        String page = pages.get(i);
        if (runNumber == i + 1) {
            stub = mockReturnDocument(stub, page, badStatusCode, badStatusMessage);
        } else {
            stub = mockReturnDocument(stub, page, goodStatusCode, goodStatusMessage);
        }
    }
}
 
private OngoingStubbing<List<BusinessPartner>> mockService() throws ODataException {
    return when(service
            .getAllBusinessPartner()
            .select(any(BusinessPartnerSelectable.class))
            .filter(BusinessPartner.BUSINESS_PARTNER_CATEGORY.eq("1"))
            .orderBy(BusinessPartner.LAST_NAME, Order.ASC)
            .execute());
}
 
@Test
public void testIsEsyProject() {
    MockVirtualFile mockEsyConfig = new MockVirtualFile(EsyPackageJsonFileType.getDefaultFilename());
    registerMockFile(mockEsyConfig);

    OngoingStubbing<Boolean> whenIsEsyPackageJson = when(EsyPackageJson.isEsyPackageJson(mockEsyConfig));

    whenIsEsyPackageJson.thenReturn(false);
    assertFalse("File not recognized as esy package.json.", ORProjectManager.isEsyProject(mockProject));

    whenIsEsyPackageJson.thenReturn(true);
    assertTrue(ORProjectManager.isEsyProject(mockProject));
}
 
源代码21 项目: astor   文件: BaseStubbing.java
public OngoingStubbing<T> thenReturn(T value, T... values) {
    OngoingStubbing<T> stubbing = thenReturn(value);            
    if (values == null) {
        return stubbing.thenReturn(null);
    }
    for (T v: values) {
        stubbing = stubbing.thenReturn(v);
    }
    return stubbing;
}
 
private void stubAcquireActiveAndKeepAlive() {
    OngoingStubbing<Future<Channel>> stubbing = Mockito.when(downstreamChannelPool.acquire(any()));
    stubbing = stubbing.thenAnswer(invocation -> {
        Promise<Channel> promise = invocation.getArgumentAt(0, Promise.class);
        Channel channel = Mockito.mock(Channel.class);
        Mockito.when(channel.isActive()).thenReturn(true);

        stubKeepAliveAttribute(channel, true);

        channels.add(channel);
        promise.setSuccess(channel);
        return promise;
    });
}
 
源代码23 项目: web3j   文件: JsonRpc2_0RxTest.java
@Test
public void testReplayBlocksDescendingFlowable() throws Exception {

    List<EthBlock> ethBlocks = Arrays.asList(createBlock(2), createBlock(1), createBlock(0));

    OngoingStubbing<EthBlock> stubbing =
            when(web3jService.send(any(Request.class), eq(EthBlock.class)));
    for (EthBlock ethBlock : ethBlocks) {
        stubbing = stubbing.thenReturn(ethBlock);
    }

    Flowable<EthBlock> flowable =
            web3j.replayPastBlocksFlowable(
                    new DefaultBlockParameterNumber(BigInteger.ZERO),
                    new DefaultBlockParameterNumber(BigInteger.valueOf(2)),
                    false,
                    false);

    CountDownLatch transactionLatch = new CountDownLatch(ethBlocks.size());
    CountDownLatch completedLatch = new CountDownLatch(1);

    List<EthBlock> results = new ArrayList<>(ethBlocks.size());
    Disposable subscription =
            flowable.subscribe(
                    result -> {
                        results.add(result);
                        transactionLatch.countDown();
                    },
                    throwable -> fail(throwable.getMessage()),
                    () -> completedLatch.countDown());

    transactionLatch.await(1, TimeUnit.SECONDS);
    assertEquals(results, (ethBlocks));

    subscription.dispose();

    completedLatch.await(1, TimeUnit.SECONDS);
    assertTrue(subscription.isDisposed());
}
 
源代码24 项目: astor   文件: BaseStubbing.java
public OngoingStubbing<T> thenReturn(T value, T... values) {
    OngoingStubbing<T> stubbing = thenReturn(value);            
    if (values == null) {
        return stubbing.thenReturn(null);
    }
    for (T v: values) {
        stubbing = stubbing.thenReturn(v);
    }
    return stubbing;
}
 
源代码25 项目: astor   文件: BaseStubbing.java
public OngoingStubbing<T> thenThrow(Throwable... throwables) {
    if (throwables == null) {
        thenThrow((Throwable) null);
    }
    OngoingStubbing<T> stubbing = null;
    for (Throwable t: throwables) {
        if (stubbing == null) {
            stubbing = thenThrow(t);                    
        } else {
            stubbing = stubbing.thenThrow(t);
        }
    }
    return stubbing;
}
 
源代码26 项目: selenium   文件: RemoteWebDriverUnitTest.java
@SafeVarargs
private final CommandExecutor prepareExecutorMock(
    Function<Command, Response>... handlers) throws IOException {
  CommandExecutor executor = mock(CommandExecutor.class);
  OngoingStubbing<Response> callChain = when(executor.execute(any()));
  for (Function<Command, Response> handler : handlers) {
    callChain = callChain.thenAnswer(invocation -> handler.apply(invocation.getArgument(0)));
  }
  return executor;
}
 
源代码27 项目: conductor   文件: AMQPObservableQueueTest.java
Channel mockChannelForQueue(Channel channel, boolean isWorking, boolean exists, String name,
		List<GetResponse> queue) throws IOException {
	// queueDeclarePassive
	final AMQImpl.Queue.DeclareOk queueDeclareOK = new AMQImpl.Queue.DeclareOk(name, queue.size(), 1);
	if (exists) {
		Mockito.when(channel.queueDeclarePassive(eq(name))).thenReturn(queueDeclareOK);
	} else {
		Mockito.when(channel.queueDeclarePassive(eq(name))).thenThrow(new IOException("Queue " + name + " exists"));
	}
	// queueDeclare
	OngoingStubbing<AMQP.Queue.DeclareOk> declareOkOngoingStubbing = Mockito.when(channel.queueDeclare(eq(name),
			Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyMap()))
			.thenReturn(queueDeclareOK);
	if (!isWorking) {
		declareOkOngoingStubbing.thenThrow(new IOException("Cannot declare queue " + name),
				new RuntimeException("Not working"));
	}
	// messageCount
	Mockito.when(channel.messageCount(eq(name))).thenReturn(1l * queue.size());
	// basicGet
	OngoingStubbing<String> getResponseOngoingStubbing = Mockito
			.when(channel.basicConsume(eq(name), Mockito.anyBoolean(), (Consumer) Mockito.any(Consumer.class))).thenAnswer(new ReturnsElementsOf(queue));
	if (!isWorking) {
		getResponseOngoingStubbing.thenThrow(new IOException("Not working"), new RuntimeException("Not working"));
	}
	// basicPublish
	if (isWorking) {
		Mockito.doNothing().when(channel).basicPublish(eq(StringUtils.EMPTY), eq(name),
				Mockito.any(AMQP.BasicProperties.class), Mockito.any(byte[].class));
	} else {
		Mockito.doThrow(new IOException("Not working")).when(channel).basicPublish(eq(StringUtils.EMPTY), eq(name),
				Mockito.any(AMQP.BasicProperties.class), Mockito.any(byte[].class));
	}
	return channel;
}
 
源代码28 项目: light-eventuate-4j   文件: EventDispatcherTest.java
@SafeVarargs
private final void whenEventHandlerDispatchReturning(CompletableFuture<Object>... results) {
  OngoingStubbing<CompletableFuture<?>> stubbing = when(eventHandler.dispatch(de));
  for (CompletableFuture<Object> r : results) {
    stubbing = stubbing.thenAnswer(invocation -> r);
  }
}
 
源代码29 项目: pentaho-hadoop-shims   文件: HBaseTableImplTest.java
private void testIOEGettingHandle( IOERunnable runnable, OngoingStubbing<HBaseConnectionHandle> ongoingStubbing )
  throws IOException {
  IOException ioException = new IOException();
  ongoingStubbing.thenThrow( ioException );
  try {
    runnable.run();
  } catch ( IOException e ) {
    assertEquals( ioException, e.getCause() );
    throw e;
  }
}
 
源代码30 项目: logback-redis   文件: JedisClientTest.java
private void withClientOnTryNumber(int tries) {
    OngoingStubbing<Optional<Jedis>> stub = when(clientProvider.getJedisClient());
    for (int i = 1; i < tries; i++) {
        stub = stub.thenReturn(Optional.empty());
    }
    stub.thenReturn(Optional.of(jedis));
}
 
 类所在包
 同包方法