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

项目:hekate    文件:MetricRegexFilterTest.java   
@Test
public void test() {
    String pattern = "test\\.test\\..*";

    MetricRegexFilter filter = new MetricRegexFilter(pattern);

    assertEquals(pattern, filter.getPattern());

    OngoingStubbing<String> stub = when(mock(Metric.class).name());

    assertTrue(filter.accept(stub.thenReturn("test.test.1").getMock()));
    assertTrue(filter.accept(stub.thenReturn("test.test.2").getMock()));

    assertFalse(filter.accept(stub.thenReturn("test1").getMock()));
    assertFalse(filter.accept(stub.thenReturn("test1test.2").getMock()));
    assertFalse(filter.accept(stub.thenReturn("invalid").getMock()));
    assertFalse(filter.accept(stub.thenReturn("invalid.test").getMock()));
}
项目:haven-search-components    文件:IdolParametricValuesServiceTest.java   
private void mockBucketResponses(final int count, final TagValue... tagValues) {
    when(element.getName()).thenReturn(
        new QName("", IdolParametricValuesServiceImpl.VALUES_NODE_NAME),
        new QName("", IdolParametricValuesServiceImpl.VALUE_NODE_NAME)
    );

    OngoingStubbing<Serializable> stub = when(element.getValue()).thenReturn(count);

    for(final TagValue tagValue : tagValues) {
        stub = stub.thenReturn(tagValue);
    }

    final GetQueryTagValuesResponseData responseData = new GetQueryTagValuesResponseData();
    final FlatField field2 = new FlatField();
    field2.getName().add("ParametricNumericDateField");
    field2.getValueAndSubvalueOrValues().add(element);
    for(final TagValue ignored : tagValues) {
        field2.getValueAndSubvalueOrValues().add(element);
    }
    responseData.getField().add(field2);

    when(queryExecutor.executeGetQueryTagValues(any(AciParameters.class), any())).thenReturn(responseData);
}
项目:intellij-ce-playground    文件: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;
}
项目:FinanceAnalytics    文件:TimeSeriesLoaderTest.java   
private SheetReader buildMockSheetReader(LocalDateDoubleTimeSeries lddts) { 

  DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
  builder.appendPattern(DATE_FORMAT);
  DateTimeFormatter dateFormat = builder.toFormatter();

  SheetReader mock = mock(SheetReader.class);
  OngoingStubbing<Map<String, String>> stub = when(mock.loadNextRow());
  for (Map.Entry<LocalDate, Double> entry : lddts) {
    Map<String, String> row = new HashMap<String, String>();
    row.put("id", EXISTING_HTSINFO_EXTERNALID.getValue());
    row.put("date", entry.getKey().toString(dateFormat));
    row.put("value", entry.getValue().toString());
    stub = stub.thenReturn(row);
  }
  stub.thenReturn(null);
  return mock;    
}
项目: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));
}
项目:powermock    文件:DefaultConstructorExpectationSetup.java   
public OngoingStubbing<T> withAnyArguments() throws Exception {
    if (mockType == null) {
        throw new IllegalArgumentException("Class to expected cannot be null");
    }
    final Class<T> unmockedType = (Class<T>) WhiteboxImpl.getUnmockedType(mockType);
    final Constructor<?>[] allConstructors = WhiteboxImpl.getAllConstructors(unmockedType);
    final Constructor<?> constructor = allConstructors[0];
    final Class<?>[] parameterTypes = constructor.getParameterTypes();
    Object[] paramArgs = new Object[parameterTypes.length];
    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> paramType = parameterTypes[i];
        paramArgs[i] = Matchers.any(paramType);
    }
    final OngoingStubbing<T> ongoingStubbing = createNewSubstituteMock(mockType, parameterTypes, paramArgs);
    Constructor<?>[] otherCtors = new Constructor<?>[allConstructors.length-1];
    System.arraycopy(allConstructors, 1, otherCtors, 0, allConstructors.length-1);
    return new DelegatingToConstructorsOngoingStubbing<T>(otherCtors, ongoingStubbing);
}
项目:powermock    文件:DelegatingToConstructorsOngoingStubbing.java   
public OngoingStubbing<T> invoke() {
    final InvocationSubstitute<T> mock = stubbing.getMock();
    for (Constructor<?> constructor : ctors) {
        final Class<?>[] parameterTypesForCtor = constructor.getParameterTypes();
        Object[] paramArgs = new Object[parameterTypesForCtor.length];
        for (int i = 0; i < parameterTypesForCtor.length; i++) {
            Class<?> paramType = parameterTypesForCtor[i];
            paramArgs[i] = Matchers.any(paramType);
        }
        try {
            final OngoingStubbing<T> when = when(mock.performSubstitutionLogic(paramArgs));
            performStubbing(when);
        } catch (Exception e) {
            throw new RuntimeException("PowerMock internal error",e);
        }
    }

    return stubbing;
}
项目:elpaaso-core    文件:DbaasServiceTestUtils.java   
/**
 * wrap when(dbaasStub.createDatabase( ...any parameters... ))
 * @param dbaasStub
 * @return a stub object representing and a call to the createDatabase method with any parameters
 * @throws Exception
 */
public static OngoingStubbing<CreateDatabaseResponseObject> whenCreateDatabase(DbaasApiRemote dbaasStub) throws Exception {
    return when(dbaasStub.createDatabase(
            anyString(), 
            anyString(),
            anyInt(), 
            any(ServiceClassWsEnum.class), 
            any(EngineWsEnum.class), 
            anyString(), 
            anyListOf(DatabaseUserInfo.class),
            any(SloWsEnum.class), 
            anyBoolean(), 
            any(UsageWsEnum.class), 
            anyString(), 
            any(NetworkZoneWsEnum.class), 
            anyString(), 
            anyString(), 
            anyString(), 
            any(BackupPlanWsEnum.class), 
            anyString(), 
            anyBoolean(), 
            anyString()));
}
项目:github-integration-plugin    文件:GitHubPRRepositoryTest.java   
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);
    }
}
项目:astor    文件:IOOBExceptionShouldNotBeThrownWhenNotCodingFluentlyTest.java   
@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());
    }
}
项目:Cheddar    文件:DefaultInMemoryMessageQueuePollerTest.java   
@Test
public void shouldPollUntilQueueEmpty_onPoll() {
    // Given
    when(mockTransactionalResourceManager.inTransaction()).thenReturn(false);
    final int messageCount = randomInt(5) + 1;
    final InMemoryMessageListener<TypedMessage> mockMemoryMessageListener = mock(InMemoryMessageListener.class);
    poller.register(mockMemoryMessageListener);

    // pollForMessage() should return true for messageCount times
    OngoingStubbing<Boolean> ongoingStubbing = when(mockMemoryMessageListener.receiveAndHandleMessages());
    for (int n = 0; n < messageCount; n++) {
        ongoingStubbing = ongoingStubbing.thenReturn(true);
    }
    ongoingStubbing.thenReturn(false);

    // When
    poller.poll();

    // Then
    verify(mockMemoryMessageListener, times(messageCount + 1)).receiveAndHandleMessages();
}
项目:SPLevo    文件:SharedTermSemanticAnalysisTest.java   
/**
 * Mock a content provider that returns for the first call to
 * {@link SemanticContentProvider#getRelevantContent(SoftwareElement, boolean)} the first list
 * of provided terms, and for the second call the second list.
 *
 * @param terms1
 *            The terms to return for the first call.
 * @param terms2
 *            The terms to return for the second call.
 * @return The prepared mock.
 * @throws UnsupportedSoftwareElementException
 */
private SemanticContentProvider mockContentProviderForTermLists(List<List<String>> termLists)
        throws UnsupportedSoftwareElementException {

    SemanticContentProvider provider = mock(SemanticContentProvider.class);
    OngoingStubbing<SemanticContent> mockStub = when(provider.getRelevantContent(any(SoftwareElement.class),
            anyBoolean()));

    for (List<String> terms : termLists) {
        SemanticContent semantic = new SemanticContent();
        for (String term : terms) {
            semantic.addCode(term);
        }
        mockStub = mockStub.thenReturn(semantic);
    }

    return provider;
}
项目:java-beetle    文件:ClientTest.java   
private List<Connection> mockedConnectionsForClient(Client client, int numConnections) throws IOException {
    final ConnectionFactory mockFactory = mock(ConnectionFactory.class);
    final OngoingStubbing<Connection> newConnectionStub = when(mockFactory.newConnection());
    List<Connection> conns = new ArrayList<Connection>(numConnections);
    // TODO OMG this is ugly. there's got to be a better way.
    OngoingStubbing<Connection> connectionOngoingStubbing = null;
    for (int i = 0; i < numConnections; i++) {
        final Connection mockConnection = mock(Connection.class);
        if (i == 0) {
            connectionOngoingStubbing = newConnectionStub.thenReturn(mockConnection);
        } else {
            connectionOngoingStubbing.thenReturn(mockConnection);
        }
        final Channel mockChannel = mock(Channel.class);
        when(mockConnection.createChannel()).thenReturn(mockChannel);
        conns.add(mockConnection);
    }
    client.setConnectionFactory(mockFactory);
    return conns;
}
项目:q-mail    文件:BoundaryGeneratorTest.java   
private Random createRandom(int... values) {
    Random random = mock(Random.class);

    OngoingStubbing<Integer> ongoingStubbing = when(random.nextInt(36));
    for (int value : values) {
        ongoingStubbing = ongoingStubbing.thenReturn(value);
    }

    return random;
}
项目:q-mail    文件:WebDavStoreTest.java   
private void configureHttpResponses(HttpResponse... responses) throws IOException {
    requestCaptor = ArgumentCaptor.forClass(HttpGeneric.class);
    OngoingStubbing<HttpResponse> stubbing =
            when(mockHttpClient.executeOverride(requestCaptor.capture(), any(HttpContext.class)));

    for (HttpResponse response : responses) {
        stubbing = stubbing.thenReturn(response);
    }
}
项目:dztools    文件:CommonUtilForTest.java   
protected <T> void makeStubFailRetriesThenSuccess(final OngoingStubbing<T> stub,
                                                  final T successValue) {
    stub
        .thenThrow(jfException)
        .thenThrow(jfException)
        .thenThrow(jfException)
        .thenReturn(successValue);
}
项目:dztools    文件:CommonUtilForTest.java   
protected <T> void makeSingleStubFailRetriesThenSuccess(final OngoingStubbing<Single<T>> stub,
                                                        final T successValue) {
    stub
        .thenReturn(Single.error(jfException))
        .thenReturn(Single.error(jfException))
        .thenReturn(Single.error(jfException))
        .thenReturn(Single.just(successValue));
}
项目:dztools    文件:CommonUtilForTest.java   
protected <T> void makeObservableStubFailRetriesThenSuccess(final OngoingStubbing<Observable<T>> stub,
                                                            final T successValue) {
    stub
        .thenReturn(Observable.error(jfException))
        .thenReturn(Observable.error(jfException))
        .thenReturn(Observable.error(jfException))
        .thenReturn(Observable.just(successValue));
}
项目:dztools    文件:HistoryWrapperTest.java   
private OngoingStubbing<List<IBar>> getStub() throws JFException {
    return when(historyMock.getBars(instrumentForTest,
                                    period,
                                    offerSide,
                                    startDate,
                                    endDate));
}
项目:lastpass-java    文件:FetcherTestLogin.java   
private WebClient SetupLogin(ResponseOrException iterationsResponseOrException,
                                           ResponseOrException loginResponseOrException)
{
    WebClient webClient = mock(WebClient.class);
    OngoingStubbing<byte[]> sequence = when(webClient.uploadValues(anyString(), Matchers.<List<KeyValuePair<String, String>>>any()));

    sequence = iterationsResponseOrException.returnOrThrow(sequence);
    if (loginResponseOrException != null)
        sequence = loginResponseOrException.returnOrThrow(sequence);

    return webClient;
}
项目:lastpass-java    文件:FetcherTest.java   
public OngoingStubbing<byte[]> returnOrThrow(OngoingStubbing<byte[]> setup)
{
    if (_exception != null)
        return setup.thenThrow(_exception);
    else
        return setup.thenReturn(_response);
}
项目:stvs    文件:TestUtils.java   
public static void mockFiles(URL ... urls) throws Exception {
  List<File> files = Arrays.stream(urls)
      .map(URL::getPath)
      .map(File::new)
      .collect(Collectors.toList());
  FileChooser chooser = Mockito.mock(FileChooser.class);
  OngoingStubbing<File> stub = Mockito.when(chooser.showOpenDialog(any()));
  for (File file : files) {
    stub = stub.thenReturn(file);
  }
  Mockito.when(chooser.getExtensionFilters()).thenReturn(FXCollections.observableList(new ArrayList<>()));
  PowerMockito.whenNew(FileChooser.class).withAnyArguments().thenReturn(chooser);
}
项目:trading4j    文件:NMovingAveragesExpertAdvisorTest.java   
private void letMovingAverageReturn(final Indicator<Price, FullMarketData<M1>> movingAverage,
        final long... values) {
    OngoingStubbing<Optional<Price>> toStub = when(movingAverage.indicate(any()));
    for (final long value : values) {
        if (value == EMPTY) {
            toStub = toStub.thenReturn(Optional.empty());
        } else {
            toStub = toStub.thenReturn(Optional.of(new Price(value)));
        }
    }
}
项目:web3j    文件:JsonRpc2_0RxTest.java   
@Test
public void testReplayBlocksObservable() throws Exception {

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

    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);

    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());
}
项目:web3j    文件: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());
}
项目:JScheme    文件:SchemeBuiltinTimesTest.java   
private void initializeMockedCallStack(SchemeObject... schemeObjects) {
    SchemeCallStack callStackMock = mock(SchemeCallStack.class);
    OngoingStubbing<SchemeObject> when = when(callStackMock.pop());
    for (SchemeObject schemeObject : schemeObjects) {
        when = when.thenReturn(schemeObject);
    }
    currentStackOngoingStubbing = when;
    PowerMockito.mockStatic(SchemeCallStack.class);
    PowerMockito.when(SchemeCallStack.instance()).thenReturn(callStackMock);
}
项目:JScheme    文件:SchemeBuiltinMinusTest.java   
private void appendPopValues(SchemeCallStack callStackMock, SchemeObject... schemeObjects) {
    OngoingStubbing<SchemeObject> when = when(callStackMock.pop());
    for (SchemeObject schemeObject : schemeObjects) {
        when = when.thenReturn(schemeObject);
    }

}
项目:K9-MailClient    文件:BoundaryGeneratorTest.java   
private Random createRandom(int... values) {
    Random random = mock(Random.class);

    OngoingStubbing<Integer> ongoingStubbing = when(random.nextInt(36));
    for (int value : values) {
        ongoingStubbing = ongoingStubbing.thenReturn(value);
    }

    return random;
}
项目:K9-MailClient    文件:WebDavStoreTest.java   
private void configureHttpResponses(HttpResponse... responses) throws IOException {
    requestCaptor = ArgumentCaptor.forClass(HttpGeneric.class);
    OngoingStubbing<HttpResponse> stubbing =
            when(mockHttpClient.executeOverride(requestCaptor.capture(), any(HttpContext.class)));

    for (HttpResponse response : responses) {
        stubbing = stubbing.thenReturn(response);
    }
}
项目: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);
  }
}
项目:beam    文件:KinesisReaderTest.java   
private void prepareRecordsWithArrivalTimestamps(long initialTimestampMs, int increment,
    int count) throws TransientKinesisException {
  long timestampMs = initialTimestampMs;
  KinesisRecord firstRecord = prepareRecordMockWithArrivalTimestamp(timestampMs);
  OngoingStubbing<CustomOptional<KinesisRecord>> shardReadersPoolStubbing =
      when(shardReadersPool.nextRecord()).thenReturn(CustomOptional.of(firstRecord));
  for (int i = 0; i < count; i++) {
    timestampMs += increment;
    KinesisRecord record = prepareRecordMockWithArrivalTimestamp(timestampMs);
    shardReadersPoolStubbing = shardReadersPoolStubbing.thenReturn(CustomOptional.of(record));
  }
  shardReadersPoolStubbing.thenReturn(CustomOptional.<KinesisRecord>absent());
}
项目:nomulus    文件:RdeUploadActionTest.java   
private static JSch createThrowingJSchSpy(JSch jsch, int numTimesToThrow) throws JSchException {
  JSch jschSpy = spy(jsch);
  OngoingStubbing<Session> stubbing =
      when(jschSpy.getSession(anyString(), anyString(), anyInt()));
  for (int i = 0; i < numTimesToThrow; i++) {
    stubbing = stubbing.thenThrow(new JSchException("The crow flies in square circles."));
  }
  stubbing.thenCallRealMethod();
  return jschSpy;
}
项目:trading4j    文件:NMovingAveragesExpertAdvisorTest.java   
private void letMovingAverageReturn(final Indicator<Price, FullMarketData<M1>> movingAverage,
        final long... values) {
    OngoingStubbing<Optional<Price>> toStub = when(movingAverage.indicate(any()));
    for (final long value : values) {
        if (value == EMPTY) {
            toStub = toStub.thenReturn(Optional.empty());
        } else {
            toStub = toStub.thenReturn(Optional.of(new Price(value)));
        }
    }
}
项目:here-aaa-java-sdk    文件:HereAccountTest.java   
/**
 * Build a mock HttpProvider that always returns the provided response body.
 */
private HttpProvider mockHttpProvider(HttpResponse... responses) throws Exception {
    HttpProvider mock = Mockito.mock(HttpProvider.class);
    OngoingStubbing<HttpResponse> stub = Mockito.when(mock.execute(Mockito.any()));
    for (HttpResponse response : responses) {
        stub = stub.thenReturn(response);
    }
    return mock;
}
项目:securemock    文件:Mockito.java   
public static <T> OngoingStubbing<T> when(final T methodCall) {
    return AccessController.doPrivileged(new PrivilegedAction<OngoingStubbing<T>>() {
        @Override
        public OngoingStubbing<T> run() {
            return org.mockito.Mockito.when(methodCall);
        }
    });
}
项目:FinanceAnalytics    文件:SecurityToFixedIncomeFutureDefinitionConverterTest.java   
@SuppressWarnings("unchecked")
private static ExchangeSource myExchangeSource() {
  final Exchange exchange = Mockito.mock(Exchange.class);
  Mockito.when(exchange.getUniqueId()).thenReturn(UniqueId.of("SOMETHING", "SOMETHING ELSE"));
  final ExchangeSource source = Mockito.mock(ExchangeSource.class);
  Mockito.when(source.get(Mockito.any(UniqueId.class))).thenReturn(exchange);
  Mockito.when(source.get(Mockito.any(ObjectId.class), Mockito.any(VersionCorrection.class))).thenReturn(exchange);
  ((OngoingStubbing) Mockito.when(source.get(Mockito.any(ExternalIdBundle.class), Mockito.any(VersionCorrection.class)))).thenReturn(Collections.singleton(exchange));
  Mockito.when(source.getSingle(Mockito.any(ExternalId.class))).thenReturn(exchange);
  Mockito.when(source.getSingle(Mockito.any(ExternalIdBundle.class))).thenReturn(exchange);
  return source;
}
项目:FinanceAnalytics    文件:SimpleSecurityResolverTest.java   
@SuppressWarnings({"unchecked", "rawtypes" })
public SimpleSecurityResolverTest() {
  _securityExternalId = ExternalId.of("Scheme1", "Value1");
  ExternalIdBundle externalIdBundle = ExternalIdBundle.of(_securityExternalId, ExternalId.of("Scheme2", "Value2"));
  _intersectingExternalIdBundle = ExternalIdBundle.of(_securityExternalId, ExternalId.of("Scheme3", "Value3"));

  _objectId = ObjectId.of("Sec", "a");

  _securityV1 = new SimpleSecurity(_objectId.atVersion("1"), externalIdBundle, "Type", "Security V1");
  _securityV2 = new SimpleSecurity(_objectId.atVersion("2"), externalIdBundle, "Type", "Security V2");

  _securityV2ValidFrom = LocalDate.of(2011, 01, 01).atStartOfDay(ZoneOffset.UTC).toInstant();

  _securitySource = mock(SecuritySource.class);

  // By unique ID
  when(_securitySource.get(_securityV1.getUniqueId())).thenReturn(_securityV1);
  when(_securitySource.get(_securityV2.getUniqueId())).thenReturn(_securityV2);
  when(_securitySource.get(UNKNOWN_UID)).thenThrow(new DataNotFoundException(""));

  // By object ID and version-correction
  when(_securitySource.get(_objectId, VersionCorrection.of(_securityV2ValidFrom.minusMillis(1), _now))).thenReturn(_securityV1);
  when(_securitySource.get(_objectId, VersionCorrection.of(_securityV2ValidFrom, _now))).thenReturn(_securityV2);
  when(_securitySource.get(UNKNOWN_OID, VersionCorrection.of(Instant.ofEpochMilli(123), Instant.ofEpochMilli(123)))).thenThrow(new DataNotFoundException(""));

  // By external ID bundle and version-correction
  ((OngoingStubbing) when(_securitySource.get(ExternalIdBundle.of(_securityExternalId), VersionCorrection.of(_securityV2ValidFrom, _now)))).thenReturn(Collections.singleton(_securityV2));
  ((OngoingStubbing) when(_securitySource.get(_intersectingExternalIdBundle, VersionCorrection.of(_securityV2ValidFrom, _now)))).thenReturn(Collections.singleton(_securityV2));
  ((OngoingStubbing) when(_securitySource.get(_intersectingExternalIdBundle, VersionCorrection.of(_securityV2ValidFrom.minusMillis(1), _now)))).thenReturn(Collections.singleton(_securityV1));
  when(_securitySource.get(UNKNOWN_BUNDLE)).thenThrow(new DataNotFoundException(""));
}
项目:powermock    文件:DefaultConstructorExpectationSetup.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> OngoingStubbing<T> createNewSubstituteMock(Class<T> type, Class<?>[] parameterTypes, Object... arguments) throws Exception {
    if (type == null) {
        throw new IllegalArgumentException("type cannot be null");
    }

    final Class<T> unmockedType = (Class<T>) WhiteboxImpl.getUnmockedType(type);
    if (parameterTypes == null) {
        WhiteboxImpl.findUniqueConstructorOrThrowException(type, arguments);
    } else {
        WhiteboxImpl.getConstructor(unmockedType, parameterTypes);
    }

    /*
    * Check if this type has been mocked before
    */
    NewInvocationControl<OngoingStubbing<T>> newInvocationControl = (NewInvocationControl<OngoingStubbing<T>>) MockRepository
            .getNewInstanceControl(unmockedType);
    if (newInvocationControl == null) {
        InvocationSubstitute<T> mock = MockCreator.mock(InvocationSubstitute.class, false, false, null, null, (Method[]) null);
        newInvocationControl = new MockitoNewInvocationControl(mock);
        MockRepository.putNewInstanceControl(type, newInvocationControl);
        MockRepository.addObjectsToAutomaticallyReplayAndVerify(WhiteboxImpl.getUnmockedType(type));
    }

    return newInvocationControl.expectSubstitutionLogic(arguments);
}
项目:powermock    文件:DefaultMethodExpectationSetup.java   
@SuppressWarnings("unchecked")
public OngoingStubbing<T> withArguments(Object firstArgument, Object... additionalArguments) throws Exception {
    if (additionalArguments == null || additionalArguments.length == 0) {
        return (OngoingStubbing<T>) Mockito.when(method.invoke(object, firstArgument));
    } else {
        return (OngoingStubbing<T>) Mockito.when(method.invoke(object, join(firstArgument, additionalArguments)));
    }
}
项目:powermock    文件:DelegatingToConstructorsOngoingStubbing.java   
public DelegatingToConstructorsOngoingStubbing(Constructor<?>[] ctors, OngoingStubbing<T> stubbing) {
    if(stubbing == null) {
        throw new IllegalArgumentException("Internal error: Ongoing stubbing must be provided");
    }
    this.ctors = ctors;
    this.stubbing = stubbing;
}