@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()));
}
java类org.mockito.stubbing.OngoingStubbing的实例源码
MetricRegexFilterTest.java 文件源码
项目:hekate
阅读 31
收藏 0
点赞 0
评论 0
IdolParametricValuesServiceTest.java 文件源码
项目:haven-search-components
阅读 27
收藏 0
点赞 0
评论 0
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);
}
PrivateResourceDetectorTest.java 文件源码
项目:intellij-ce-playground
阅读 24
收藏 0
点赞 0
评论 0
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;
}
TimeSeriesLoaderTest.java 文件源码
项目:FinanceAnalytics
阅读 27
收藏 0
点赞 0
评论 0
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;
}
TestKiteExtractor.java 文件源码
项目:sqoop-on-spark
阅读 26
收藏 0
点赞 0
评论 0
@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));
}
DefaultConstructorExpectationSetup.java 文件源码
项目:powermock
阅读 28
收藏 0
点赞 0
评论 0
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);
}
DelegatingToConstructorsOngoingStubbing.java 文件源码
项目:powermock
阅读 27
收藏 0
点赞 0
评论 0
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;
}
DbaasServiceTestUtils.java 文件源码
项目:elpaaso-core
阅读 26
收藏 0
点赞 0
评论 0
/**
* 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()));
}
GitHubPRRepositoryTest.java 文件源码
项目:github-integration-plugin
阅读 31
收藏 0
点赞 0
评论 0
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);
}
}
IOOBExceptionShouldNotBeThrownWhenNotCodingFluentlyTest.java 文件源码
项目:astor
阅读 19
收藏 0
点赞 0
评论 0
@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());
}
}
DefaultInMemoryMessageQueuePollerTest.java 文件源码
项目:Cheddar
阅读 26
收藏 0
点赞 0
评论 0
@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();
}
SharedTermSemanticAnalysisTest.java 文件源码
项目:SPLevo
阅读 26
收藏 0
点赞 0
评论 0
/**
* 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;
}
ClientTest.java 文件源码
项目:java-beetle
阅读 29
收藏 0
点赞 0
评论 0
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;
}
BoundaryGeneratorTest.java 文件源码
项目:q-mail
阅读 28
收藏 0
点赞 0
评论 0
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;
}
WebDavStoreTest.java 文件源码
项目:q-mail
阅读 31
收藏 0
点赞 0
评论 0
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);
}
}
CommonUtilForTest.java 文件源码
项目:dztools
阅读 27
收藏 0
点赞 0
评论 0
protected <T> void makeStubFailRetriesThenSuccess(final OngoingStubbing<T> stub,
final T successValue) {
stub
.thenThrow(jfException)
.thenThrow(jfException)
.thenThrow(jfException)
.thenReturn(successValue);
}
CommonUtilForTest.java 文件源码
项目:dztools
阅读 24
收藏 0
点赞 0
评论 0
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));
}
CommonUtilForTest.java 文件源码
项目:dztools
阅读 25
收藏 0
点赞 0
评论 0
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));
}
HistoryWrapperTest.java 文件源码
项目:dztools
阅读 142
收藏 0
点赞 0
评论 0
private OngoingStubbing<List<IBar>> getStub() throws JFException {
return when(historyMock.getBars(instrumentForTest,
period,
offerSide,
startDate,
endDate));
}
FetcherTestLogin.java 文件源码
项目:lastpass-java
阅读 32
收藏 0
点赞 0
评论 0
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;
}
FetcherTest.java 文件源码
项目:lastpass-java
阅读 27
收藏 0
点赞 0
评论 0
public OngoingStubbing<byte[]> returnOrThrow(OngoingStubbing<byte[]> setup)
{
if (_exception != null)
return setup.thenThrow(_exception);
else
return setup.thenReturn(_response);
}
TestUtils.java 文件源码
项目:stvs
阅读 27
收藏 0
点赞 0
评论 0
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);
}
NMovingAveragesExpertAdvisorTest.java 文件源码
项目:trading4j
阅读 29
收藏 0
点赞 0
评论 0
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)));
}
}
}
JsonRpc2_0RxTest.java 文件源码
项目:web3j
阅读 25
收藏 0
点赞 0
评论 0
@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());
}
JsonRpc2_0RxTest.java 文件源码
项目:web3j
阅读 24
收藏 0
点赞 0
评论 0
@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());
}
SchemeBuiltinTimesTest.java 文件源码
项目:JScheme
阅读 24
收藏 0
点赞 0
评论 0
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);
}
SchemeBuiltinMinusTest.java 文件源码
项目:JScheme
阅读 27
收藏 0
点赞 0
评论 0
private void appendPopValues(SchemeCallStack callStackMock, SchemeObject... schemeObjects) {
OngoingStubbing<SchemeObject> when = when(callStackMock.pop());
for (SchemeObject schemeObject : schemeObjects) {
when = when.thenReturn(schemeObject);
}
}
BoundaryGeneratorTest.java 文件源码
项目:K9-MailClient
阅读 22
收藏 0
点赞 0
评论 0
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;
}
WebDavStoreTest.java 文件源码
项目:K9-MailClient
阅读 27
收藏 0
点赞 0
评论 0
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);
}
}
EventDispatcherTest.java 文件源码
项目:light-eventuate-4j
阅读 27
收藏 0
点赞 0
评论 0
@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);
}
}