下面列出了怎么用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;
}
});
}
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;
}
/**
* 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()));
}
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());
}
}
@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);
}
}
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);
}
}
@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());
}
@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());
}
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);
}
@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);
}
}
}
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;
}
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;
}
@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));
}
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;
});
}
@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());
}
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;
}
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;
}
@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;
}
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;
}
@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);
}
}
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;
}
}
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));
}