org.mockito.Mockito.atMost()方法的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(15.8k)|赞(0)|评价(0)|浏览(190)

本文整理了Java中org.mockito.Mockito.atMost()方法的一些代码示例,展示了Mockito.atMost()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Mockito.atMost()方法的具体详情如下:
包路径:org.mockito.Mockito
类名称:Mockito
方法名:atMost

Mockito.atMost介绍

[英]Allows at-most-x verification. E.g:

verify(mock, atMost(3)).someMethod("some arg");

See examples in javadoc for Mockito class
[中]最多允许x次验证。例如:

verify(mock, atMost(3)).someMethod("some arg");

参见javadoc中Mockito类的示例

代码示例

代码示例来源:origin: apache/incubator-gobblin

public void retryTestNonTransientException() throws IOException {
 DataWriter<Void> writer = mock(DataWriter.class);
 doThrow(new NonTransientException()).when(writer).writeEnvelope(any(RecordEnvelope.class));
 DataWriterWrapperBuilder<Void> builder = new DataWriterWrapperBuilder<>(writer, new State());
 DataWriter<Void> retryWriter = builder.build();
 try {
  retryWriter.writeEnvelope(new RecordEnvelope<>(null));
  Assert.fail("Should have failed.");
 } catch (Exception e) { }
 verify(writer, atMost(1)).writeEnvelope(any(RecordEnvelope.class));
}

代码示例来源:origin: pentaho/pentaho-kettle

@Test
public void testGetFields() throws Exception {
 TransExecutorMeta meta = new TransExecutorMeta();
 meta = spy( meta );
 StepMeta nextStep = mock( StepMeta.class );
 // Test null
 meta.getFields( null, null, null, nextStep, null, null, null );
 verify( meta, never() ).addFieldToRow( any( RowMetaInterface.class ), anyString(), anyInt() );
 RowMetaInterface rowMeta = mock( RowMetaInterface.class );
 meta.getFields( rowMeta, null, null, nextStep, null, null, null );
 verify( rowMeta, never() ).clear();
 StepMeta executionResultTargetStepMeta = mock( StepMeta.class );
 meta.setExecutionResultTargetStepMeta( executionResultTargetStepMeta );
 meta.getFields( rowMeta, null, null, nextStep, null, null, null );
 verify( rowMeta, atMost( 1 ) ).clear();
 meta.setExecutionResultTargetStepMeta( null );
 StepMeta resultFilesTargetStepMeta = mock( StepMeta.class );
 meta.setResultFilesTargetStepMeta( resultFilesTargetStepMeta );
 meta.getFields( rowMeta, null, null, nextStep, null, null, null );
 verify( rowMeta, atMost( 1 ) ).clear();
 meta.setResultFilesTargetStepMeta( null );
 StepMeta outputRowsSourceStepMeta = mock( StepMeta.class );
 meta.setOutputRowsSourceStepMeta( outputRowsSourceStepMeta );
 meta.getFields( rowMeta, null, null, nextStep, null, null, null );
 verify( rowMeta, atMost( 1 ) ).clear();
 meta.setOutputRowsSourceStepMeta( null );
}

代码示例来源:origin: googleapis/google-cloud-java

@Test
public void atMostMaxSessionsCreated() {
 setupMockSessionCreation();
 AtomicBoolean failed = new AtomicBoolean(false);
 pool = createPool();
 int numSessions = 10;
 final CountDownLatch latch = new CountDownLatch(numSessions);
 for (int i = 0; i < numSessions; i++) {
  getSessionAsync(latch, failed);
 }
 Uninterruptibles.awaitUninterruptibly(latch);
 verify(client, atMost(options.getMaxSessions())).createSession(db);
 assertThat(failed.get()).isFalse();
}

代码示例来源:origin: gocd/gocd

@Test
public void shouldNotifyListenerOfMultiplePluginFilesRemoved() throws Exception {
  monitor.addPluginJarChangeListener(changeListener);
  monitor.start();
  copyPluginToThePluginDirectory(bundledPluginDir, "descriptor-aware-test-plugin-1.jar");
  copyPluginToThePluginDirectory(bundledPluginDir, "descriptor-aware-test-plugin-2.jar");
  copyPluginToThePluginDirectory(bundledPluginDir, "descriptor-aware-test-plugin-3.jar");
  waitUntilNextRun(monitor);
  verify(changeListener).pluginJarAdded(pluginFileDetails(bundledPluginDir, "descriptor-aware-test-plugin-1.jar", true));
  verify(changeListener).pluginJarAdded(pluginFileDetails(bundledPluginDir, "descriptor-aware-test-plugin-2.jar", true));
  verify(changeListener).pluginJarAdded(pluginFileDetails(bundledPluginDir, "descriptor-aware-test-plugin-3.jar", true));
  FileUtils.deleteQuietly(new File(bundledPluginDir, "descriptor-aware-test-plugin-1.jar"));
  FileUtils.deleteQuietly(new File(bundledPluginDir, "descriptor-aware-test-plugin-2.jar"));
  waitUntilNextRun(monitor);
  verify(changeListener, atMost(1)).pluginJarUpdated(pluginFileDetails(bundledPluginDir, "descriptor-aware-test-plugin-1.jar", true));
  verify(changeListener, atMost(1)).pluginJarUpdated(pluginFileDetails(bundledPluginDir, "descriptor-aware-test-plugin-2.jar", true));
  verify(changeListener).pluginJarRemoved(pluginFileDetails(bundledPluginDir, "descriptor-aware-test-plugin-1.jar", true));
  verify(changeListener).pluginJarRemoved(pluginFileDetails(bundledPluginDir, "descriptor-aware-test-plugin-2.jar", true));
  verifyNoMoreInteractions(changeListener);
}

代码示例来源:origin: neo4j/neo4j

private void defrag( int nodeCount, RecordStore<RelationshipGroupRecord> groupStore )
{
  Monitor monitor = mock( Monitor.class );
  RelationshipGroupDefragmenter defragmenter = new RelationshipGroupDefragmenter( CONFIG,
      ExecutionMonitors.invisible(), monitor, AUTO_WITHOUT_PAGECACHE );
  // Calculation below correlates somewhat to calculation in RelationshipGroupDefragmenter.
  // Anyway we verify below that we exercise the multi-pass bit, which is what we want
  long memory = groupStore.getHighId() * 15 + 200;
  defragmenter.run( memory, stores, nodeCount );
  // Verify that we exercise the multi-pass functionality
  verify( monitor, atLeast( 2 ) ).defragmentingNodeRange( anyLong(), anyLong() );
  verify( monitor, atMost( 10 ) ).defragmentingNodeRange( anyLong(), anyLong() );
}

代码示例来源:origin: Netflix/conductor

@Test
public void testEventProcessorWithNonRetriableError() {
  EventHandler eventHandler = new EventHandler();
  eventHandler.setName(UUID.randomUUID().toString());
  eventHandler.setActive(true);
  eventHandler.setEvent(event);
  Action completeTaskAction = new Action();
  completeTaskAction.setAction(Type.complete_task);
  completeTaskAction.setComplete_task(new TaskDetails());
  completeTaskAction.getComplete_task().setTaskRefName("task_x");
  completeTaskAction.getComplete_task().setWorkflowId(UUID.randomUUID().toString());
  completeTaskAction.getComplete_task().setOutput(new HashMap<>());
  eventHandler.getActions().add(completeTaskAction);
  when(metadataService.getEventHandlers()).thenReturn(Collections.singletonList(eventHandler));
  when(metadataService.getEventHandlersForEvent(event, true)).thenReturn(Collections.singletonList(eventHandler));
  when(executionService.addEventExecution(any())).thenReturn(true);
  when(actionProcessor.execute(any(), any(), any(), any())).thenThrow(new ApplicationException(ApplicationException.Code.INVALID_INPUT, "some non-retriable error"));
  EventProcessor eventProcessor = new EventProcessor(executionService, metadataService, actionProcessor, eventQueues, jsonUtils, new TestConfiguration());
  assertNotNull(eventProcessor.getQueues());
  assertEquals(1, eventProcessor.getQueues().size());
  Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
  verify(queue, atMost(1)).ack(any());
  verify(queue, never()).publish(any());
}

代码示例来源:origin: real-logic/aeron

any(Header.class));
verify(fragmentHandlerB, atMost(numMessagesToSend - 1)).onFragment(
  any(DirectBuffer.class),
  anyInt(),

代码示例来源:origin: apache/hbase

waitAndVerifyProc(coordinatorTask, once, never(), once, atMost(1), true);
verifyCohortSuccessful(expected, subprocFactory, cohortTasks, once, never(), once,
 once, true);

代码示例来源:origin: Netflix/conductor

assertTrue(completed.get());
verify(queue, atMost(1)).ack(any());
verify(queue, never()).publish(any());

代码示例来源:origin: kiegroup/optaplanner

verify(childValueSelector, atMost(4)).iterator(any());
verify(childValueSelector, atMost(4)).getSize(any());

代码示例来源:origin: kiegroup/optaplanner

verify(childValueSelector, atMost(4)).iterator(any());
verify(childValueSelector, atMost(4)).getSize(any());

代码示例来源:origin: hugegraph/hugegraph

@Test
public void testCacheGetPut() {
  final String name = "test-cache";
  CacheManager manager = CacheManager.instance();
  Mockito.when(this.mockCaches.containsKey(name)).thenReturn(false);
  final Cache[] cache = new Cache[1];
  Mockito.when(this.mockCaches.putIfAbsent(Mockito.anyString(), Mockito.any()))
      .thenAnswer(i -> cache[0] = (Cache) i.getArguments()[1]);
  Mockito.when(this.mockCaches.get(name)).thenAnswer(i -> cache[0]);
  Cache cache1 = manager.cache(name);
  Assert.assertNotNull(cache1);
  Mockito.verify(this.mockCaches).putIfAbsent(name, cache1);
  Mockito.when(this.mockCaches.containsKey(name)).thenReturn(true);
  Mockito.when(this.mockCaches.get(name)).thenReturn(cache1);
  Cache cache2 = manager.cache(name);
  Assert.assertSame(cache1, cache2);
  Mockito.verify(this.mockCaches, Mockito.atMost(1))
      .putIfAbsent(Mockito.anyString(), Mockito.any());
}

代码示例来源:origin: hugegraph/hugegraph

@Test
public void testCachePutGetWithCapacity() {
  final String name = "test-cache";
  final int capacity = 12345;
  CacheManager manager = CacheManager.instance();
  Mockito.when(this.mockCaches.containsKey(name)).thenReturn(false);
  final Cache[] cache = new Cache[1];
  Mockito.when(this.mockCaches.putIfAbsent(Mockito.anyString(), Mockito.any()))
      .thenAnswer(i -> cache[0] = (Cache) i.getArguments()[1]);
  Mockito.when(this.mockCaches.get(name)).thenAnswer(i -> cache[0]);
  Cache cache1 = manager.cache(name, capacity);
  Assert.assertNotNull(cache1);
  Assert.assertEquals(capacity, cache1.capacity());
  Mockito.verify(this.mockCaches).putIfAbsent(name, cache1);
  Mockito.when(this.mockCaches.containsKey(name)).thenReturn(true);
  Mockito.when(this.mockCaches.get(name)).thenReturn(cache1);
  Cache cache2 = manager.cache(name, capacity);
  Assert.assertEquals(capacity, cache2.capacity());
  Assert.assertSame(cache1, cache2);
  Assert.assertSame(cache1, manager.cache(name));
  Assert.assertSame(cache1, manager.cache(name, 0));
  Assert.assertSame(cache1, manager.cache(name, 1));
  Assert.assertSame(cache1, manager.cache(name, capacity));
  Assert.assertSame(cache1, manager.cache(name, capacity + 10));
  Mockito.verify(this.mockCaches, Mockito.atMost(1))
      .putIfAbsent(Mockito.anyString(), Mockito.any());
}

代码示例来源:origin: haraldk/TwelveMonkeys

verify(response, atMost(1)).setContentLength(stream.size()); // setContentLength not implemented, avoid future bugs
verify(out, atLeastOnce()).flush();

代码示例来源:origin: palantir/atlasdb

@Test
public void extraSweepersGiveUpAfterFailingToAcquireEnoughTimes() throws InterruptedException {
  int shards = 16;
  int sweepers = 4;
  int threads = shards / (sweepers / 2);
  TimelockService stickyLockService = createStickyLockService();
  createAndInitializeSweepersAndWaitForOneBackgroundIteration(sweepers, shards, threads, stickyLockService);
  ArgumentCaptor<LockRequest> captor = ArgumentCaptor.forClass(LockRequest.class);
  // minimum: as in the example above, but we have extra threads
  // threads + ... + threads * (shards / threads) + shards * (threads * sweepers - shards)
  verify(stickyLockService, atLeast(shards * (shards / threads + 1) / 2 + shards * (threads * sweepers - shards)))
      .lock(captor.capture());
  // maximum: one would think that it is
  // shards + shards - 1 + ... + shards - (sweepers - 1) + shards * (threads * sweepers - shards)
  // but actually the logic is much more complicated since threads from the same sweeper can loop back and hit a
  // race condition with each other, so we go with the more conservative upper bound
  verify(stickyLockService, atMost(threads * sweepers * shards)).lock(any());
  Set<String> requestedLockIds = captor.getAllValues().stream()
      .map(LockRequest::getLockDescriptors)
      .map(Iterables::getOnlyElement)
      .map(LockDescriptor::getLockIdAsString)
      .collect(Collectors.toSet());
  Set<String> expectedLockIds = IntStream.range(0, shards).boxed()
      .map(ShardAndStrategy::conservative)
      .map(ShardAndStrategy::toText)
      .collect(Collectors.toSet());
  assertThat(requestedLockIds).hasSameElementsAs(expectedLockIds);
}

代码示例来源:origin: palantir/atlasdb

@Test
public void batchesConcurrentRequests() throws InterruptedException {
  freezableDelegate.freeze();
  AsyncTasks initialTask = getConcurrently(1);
  AsyncTasks batch = getConcurrently(5);
  freezableDelegate.unfreeze();
  batch.await();
  // At least some of these requests should be batched. We can't guarantee it will always be 2 though, if
  // we get really unlucky with scheduling.
  verify(delegate, atLeast(2)).get();
  verify(delegate, atMost(5)).get();
}

代码示例来源:origin: palantir/atlasdb

@Test
public void multipleSweepersSweepDifferentShardsAndCallUnlockAfterwards() throws InterruptedException {
  int shards = 128;
  int sweepers = 8;
  int threads = shards / sweepers;
  TimelockService stickyLockService = createStickyLockService();
  createAndInitializeSweepersAndWaitForOneBackgroundIteration(sweepers, shards, threads, stickyLockService);
  for (int i = 0; i < shards; i++) {
    assertProgressUpdatedToTimestamp(maxTsForFinePartition(tsPartitionFine(unreadableTs - 1)), i);
    verify(stickyLockService, times(1)).unlock(ImmutableSet.of(LockToken.of(new UUID(i, 0L))));
  }
  // minimum: all threads on one host succeed, then on another, etc:
  // threads + threads * 2 + ...  + threads * swepers
  verify(stickyLockService, atLeast(threads * sweepers * (sweepers - 1) / 2))
      .lock(any(LockRequest.class));
  // maximum: all but one succeed on each host, and only then those succeed:
  // shards + shards - 1 + ... + shards - (sweepers - 1)
  verify(stickyLockService, atMost(sweepers * shards - sweepers * (sweepers - 1) / 2))
      .lock(any(LockRequest.class));
}

代码示例来源:origin: mulesoft/mule

@Test
@Description("When configured with delayErrors='false' the first errors causes strategy to throw this exception. Other routes may or may not be executed depending on concurrency.")
public void errorEagerConcurrent() throws Throwable {
 strategy = createStrategy(processingStrategy, 4, false, MAX_VALUE);
 Processor processorSpy = createProcessorSpy(of(1));
 Processor processorSpy2 = createProcessorSpy(of(2));
 Processor processorSpy3 = createProcessorSpy(of(3));
 CoreEvent orignial = testEvent();
 RuntimeException exception = new IllegalStateException();
 RoutingPair failingPair = of(orignial, createFailingRoutingPair(exception));
 RoutingPair okPair = of(orignial, createChain(processorSpy));
 RoutingPair okPair2 = of(orignial, createChain(processorSpy2));
 RoutingPair okPair3 = of(orignial, createChain(processorSpy3));
 expectedException.expect(instanceOf(MessagingException.class));
 expectedException.expectCause(is(exception));
 invokeStrategyBlocking(strategy, testEvent(), asList(failingPair, okPair, okPair2, okPair3), throwable -> {
  verify(processorSpy, atMost(1)).process(any(CoreEvent.class));
  verify(processorSpy2, atMost(1)).process(any(CoreEvent.class));
  verify(processorSpy3, atMost(1)).process(any(CoreEvent.class));
 });
}

代码示例来源:origin: spring-projects/spring-integration

@Test
public void ensurePollerTaskStops() throws Exception {
  final CountDownLatch latch = new CountDownLatch(1);
  QueueChannel channel = new QueueChannel();
  channel.send(new GenericMessage<>("foo"));
  //Has to be an explicit implementation - Mockito cannot mock/spy lambdas
  MessageHandler handler = Mockito.spy(new MessageHandler() {
    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
      latch.countDown();
    }
  });
  PollingConsumer consumer = new PollingConsumer(channel, handler);
  consumer.setTrigger(new PeriodicTrigger(0));
  consumer.setErrorHandler(errorHandler);
  consumer.setTaskScheduler(taskScheduler);
  consumer.setBeanFactory(mock(BeanFactory.class));
  consumer.afterPropertiesSet();
  consumer.start();
  assertTrue(latch.await(2, TimeUnit.SECONDS));
  Mockito.verify(handler, times(1)).handleMessage(Mockito.any(Message.class));
  consumer.stop();
  Mockito.reset(handler);
  for (int i = 0; i < 10; i++) {
    channel.send(new GenericMessage<>("foo"));
  }
  Mockito.verify(handler, atMost(1)).handleMessage(Mockito.any(Message.class));
}

代码示例来源:origin: haraldk/TwelveMonkeys

@Test
public void testEmbeddedBeforeBaseURI() throws URISyntaxException, IOException {
  // Asking for metadata, width, height etc, before attempting to read using a param,
  // will cause the document to be parsed without a base URI.
  // This will work, but may not use the CSS...
  URL resource = getClassLoaderResource("/svg/barChart.svg");
  SVGImageReader reader = createReader();
  TestData data = new TestData(resource, (Dimension) null);
  try (ImageInputStream stream = data.getInputStream()) {
    reader.setInput(stream);
    IIOReadWarningListener listener = mock(IIOReadWarningListener.class);
    reader.addIIOReadWarningListener(listener);
    assertEquals(450, reader.getWidth(0));
    assertEquals(500, reader.getHeight(0));
    // Expect the warning about the missing CSS
    verify(listener, atMost(1)).warningOccurred(any(ImageReader.class), anyString());
    reset(listener);
    SVGReadParam param = reader.getDefaultReadParam();
    param.setBaseURI(resource.toURI().toASCIIString());
    BufferedImage image = reader.read(0, param);
    assertNotNull(image);
    assertEquals(450, image.getWidth());
    assertEquals(500, image.getHeight());
    // No more warnings now that the base URI is set
    verifyZeroInteractions(listener);
  }
  finally {
    reader.dispose();
  }
}

相关文章