org.mockito.stubbing.OngoingStubbing Java Examples
The following examples show how to use
org.mockito.stubbing.OngoingStubbing.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpaceraceTest.java From codenjoy with GNU General Public License v3.0 | 6 votes |
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); } }
Example #2
Source File: LoadBalancerTests.java From titus-control-plane with Apache License 2.0 | 6 votes |
/** * 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())); }
Example #3
Source File: PrivateResourceDetectorTest.java From javaide with GNU General Public License v3.0 | 6 votes |
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; }
Example #4
Source File: TestQueryElasticsearchHttp.java From localization_nifi with Apache License 2.0 | 6 votes |
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; } }); }
Example #5
Source File: TestKiteExtractor.java From sqoop-on-spark with Apache License 2.0 | 6 votes |
@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)); }
Example #6
Source File: TestQueryElasticsearchHttp.java From nifi with Apache License 2.0 | 6 votes |
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; } }); }
Example #7
Source File: GitHubPRRepositoryTest.java From github-integration-plugin with MIT License | 6 votes |
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); } }
Example #8
Source File: JsonRpc2_0RxTest.java From client-sdk-java with Apache License 2.0 | 6 votes |
@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()); }
Example #9
Source File: IOOBExceptionShouldNotBeThrownWhenNotCodingFluentlyTest.java From astor with GNU General Public License v2.0 | 6 votes |
@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()); } }
Example #10
Source File: JsonRpc2_0RxTest.java From client-sdk-java with Apache License 2.0 | 5 votes |
@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()); }
Example #11
Source File: TestQueryElasticsearchHttp.java From localization_nifi with Apache License 2.0 | 5 votes |
@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); } } }
Example #12
Source File: RetryingHttpClientExecutorTest.java From salt-step with BSD 3-Clause "New" or "Revised" License | 5 votes |
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); }
Example #13
Source File: TestScrollElasticsearchHttp.java From nifi with Apache License 2.0 | 5 votes |
@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); } } }
Example #14
Source File: JsonRpc2_0RxTest.java From etherscan-explorer with GNU General Public License v3.0 | 5 votes |
@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()); }
Example #15
Source File: TestScrollElasticsearchHttp.java From localization_nifi with Apache License 2.0 | 5 votes |
@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); } } }
Example #16
Source File: HBaseTableImplTest.java From pentaho-hadoop-shims with Apache License 2.0 | 5 votes |
private void testIOEClosingHandle( IOERunnable runnable, OngoingStubbing<HBaseConnectionHandle> ongoingStubbing ) throws IOException { IOException ioException = new IOException(); ongoingStubbing.thenReturn( hBaseConnectionHandle ); doThrow( ioException ).when( hBaseConnectionHandle ).close(); try { runnable.run(); } catch ( IOException e ) { assertEquals( ioException, e.getCause() ); throw e; } }
Example #17
Source File: SearchTransformStreamTest.java From heroic with Apache License 2.0 | 5 votes |
public void setSearchHitPages(SearchHit[]... pages) { OngoingStubbing<SearchHit[]> stub = when(searchHits.getHits()); for (final SearchHit[] page : pages) { stub = stub.thenReturn(page); } }
Example #18
Source File: HealthCheckedChannelPoolTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
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; }); }
Example #19
Source File: BaseStubbing.java From astor with GNU General Public License v2.0 | 5 votes |
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; }
Example #20
Source File: GitHubPRRepositoryTest.java From github-integration-plugin with MIT License | 5 votes |
private void getAllPrBuildsNonNullCauseExpectations(int size) { when(run.getCause(GitHubPRCause.class)).thenReturn(cause); OngoingStubbing<Integer> expectation = null; for (int i = 0; i < size; i++) { if (expectation == null) { expectation = when(cause.getNumber()).thenReturn(i); } else { expectation.thenReturn(i); } } }
Example #21
Source File: JsonRpc2_0RxTest.java From web3j with Apache License 2.0 | 5 votes |
@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()); }
Example #22
Source File: BaseStubbing.java From astor with GNU General Public License v2.0 | 5 votes |
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; }
Example #23
Source File: BaseStubbing.java From astor with GNU General Public License v2.0 | 5 votes |
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; }
Example #24
Source File: RemoteWebDriverUnitTest.java From selenium with Apache License 2.0 | 5 votes |
@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; }
Example #25
Source File: AMQPObservableQueueTest.java From conductor with Apache License 2.0 | 5 votes |
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; }
Example #26
Source File: EventDispatcherTest.java From light-eventuate-4j with Apache License 2.0 | 5 votes |
@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); } }
Example #27
Source File: JedisClientTest.java From logback-redis with Apache License 2.0 | 5 votes |
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)); }
Example #28
Source File: BaseStubbing.java From astor with GNU General Public License v2.0 | 5 votes |
public OngoingStubbing<T> thenThrow(Class<? extends Throwable>... throwableClasses) { if (throwableClasses == null) { thenThrow((Throwable) null); } OngoingStubbing<T> stubbing = null; for (Class<? extends Throwable> t: throwableClasses) { if (stubbing == null) { stubbing = thenThrow(t); } else { stubbing = stubbing.thenThrow(t); } } return stubbing; }
Example #29
Source File: OngoingStubbingImpl.java From astor with GNU General Public License v2.0 | 5 votes |
public OngoingStubbing<T> thenAnswer(Answer<?> answer) { if(!invocationContainerImpl.hasInvocationForPotentialStubbing()) { new Reporter().incorrectUseOfApi(); } invocationContainerImpl.addAnswer(answer); return new ConsecutiveStubbing<T>(invocationContainerImpl); }
Example #30
Source File: HBaseTableImplTest.java From pentaho-hadoop-shims with Apache License 2.0 | 5 votes |
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; } }