@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())); }
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); }
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; }
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; }
@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)); }
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); }
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; }
/** * 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())); }
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); } }
@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 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(); }
/** * 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; }
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; }
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; }
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); } }
protected <T> void makeStubFailRetriesThenSuccess(final OngoingStubbing<T> stub, final T successValue) { stub .thenThrow(jfException) .thenThrow(jfException) .thenThrow(jfException) .thenReturn(successValue); }
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)); }
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)); }
private OngoingStubbing<List<IBar>> getStub() throws JFException { return when(historyMock.getBars(instrumentForTest, period, offerSide, startDate, endDate)); }
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; }
public OngoingStubbing<byte[]> returnOrThrow(OngoingStubbing<byte[]> setup) { if (_exception != null) return setup.thenThrow(_exception); else return setup.thenReturn(_response); }
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); }
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))); } } }
@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()); }
@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()); }
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); }
private void appendPopValues(SchemeCallStack callStackMock, SchemeObject... schemeObjects) { OngoingStubbing<SchemeObject> when = when(callStackMock.pop()); for (SchemeObject schemeObject : schemeObjects) { when = when.thenReturn(schemeObject); } }
@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 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()); }
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; }
/** * 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; }
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); } }); }
@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; }
@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("")); }
@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); }
@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))); } }
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; }