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

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

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

Mockito.doAnswer介绍

[英]Use doAnswer() when you want to stub a void method with generic Answer.

Stubbing voids requires different approach from Mockito#when(Object) because the compiler does not like void methods inside brackets...

Example:

doAnswer(new Answer() { 
public Object answer(InvocationOnMock invocation) { 
Object[] args = invocation.getArguments(); 
Mock mock = invocation.getMock(); 
return null; 
}}) 
.when(mock).someMethod();

See examples in javadoc for Mockito class
[中]当您想用泛型答案存根一个void方法时,请使用doAnswer()
stubing void需要与Mockito#when(Object)不同的方法,因为编译器不喜欢括号内的void方法。。。
例子:

doAnswer(new Answer() { 
public Object answer(InvocationOnMock invocation) { 
Object[] args = invocation.getArguments(); 
Mock mock = invocation.getMock(); 
return null; 
}}) 
.when(mock).someMethod();

有关Mockito类,请参见javadoc中的示例

代码示例

代码示例来源:origin: ReactiveX/RxJava

/**
 * Mocks a subscriber and prepares it to request Long.MAX_VALUE.
 * @param <T> the value type
 * @return the mocked subscriber
 */
@SuppressWarnings("unchecked")
public static <T> FlowableSubscriber<T> mockSubscriber() {
  FlowableSubscriber<T> w = mock(FlowableSubscriber.class);
  Mockito.doAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock a) throws Throwable {
      Subscription s = a.getArgument(0);
      s.request(Long.MAX_VALUE);
      return null;
    }
  }).when(w).onSubscribe((Subscription)any());
  return w;
}

代码示例来源:origin: square/picasso

static Resources mockResources(final String resValueString) {
 Resources resources = mock(Resources.class);
 doAnswer(new Answer<Void>() {
  @Override public Void answer(InvocationOnMock invocation) {
   Object[] args = invocation.getArguments();
   ((TypedValue) args[1]).string = resValueString;
   return null;
  }
 }).when(resources).getValue(anyInt(), any(TypedValue.class), anyBoolean());
 return resources;
}

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

private static ExecutorService sameThreadExecutor() throws InterruptedException
{
  ExecutorService executor = immediateExecutor();
  when( executor.awaitTermination( anyLong(), any() ) ).thenReturn( true );
  doAnswer( invocation ->
  {
    ((Runnable) invocation.getArgument( 0 )).run();
    return null;
  } ).when( executor ).execute( any() );
  return executor;
}

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

@Test
public void uploadArtifacts() throws Exception {
  AtomicOutputStream mockOutputStream = mock(AtomicOutputStream.class);
  doNothing().when(mockOutputStream).cancel();
  final AtomicInteger counter = new AtomicInteger();
  final Answer incrementCounter = new Answer() {
    public Object answer(InvocationOnMock invocation) throws Throwable {
      counter.addAndGet(1);
      return null;
    }
  };
  doAnswer(incrementCounter).when(mockOutputStream).write(anyInt());
  doAnswer(incrementCounter).when(mockOutputStream).write(any(byte[].class));
  doAnswer(incrementCounter).when(mockOutputStream).write(any(byte[].class), anyInt(), anyInt());
  doNothing().when(mockOutputStream).close();
  when(mockBlobStore.getBlobMeta(anyString())).thenThrow(new KeyNotFoundException());
  when(mockBlobStore.createBlob(anyString(), any(SettableBlobMeta.class))).thenReturn(mockOutputStream);
  String artifact = "group:artifact:1.0.0";
  String expectedBlobKeyForArtifact = "group-artifact-1.0.0.jar";
  File mockFile = createTemporaryDummyFile();
  Map<String, File> artifacts = new LinkedHashMap<>();
  artifacts.put(artifact, mockFile);
  List<String> keys = sut.uploadArtifacts(artifacts);
  assertEquals(1, keys.size());
  assertTrue(keys.get(0).contains(expectedBlobKeyForArtifact));
  assertTrue(counter.get() > 0);
  verify(mockOutputStream).close();
}

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

@Test
public void testWindowStateNotAvailableToMergingWindows() throws Exception {
  WindowAssigner<Integer, TimeWindow> mockAssigner = mockMergingAssigner();
  Trigger<Integer, TimeWindow> mockTrigger = mockTrigger();
  InternalWindowFunction<Iterable<Integer>, Void, Integer, TimeWindow> mockWindowFunction = mockWindowFunction();
  KeyedOneInputStreamOperatorTestHarness<Integer, Integer, Void> testHarness =
    createWindowOperator(mockAssigner, mockTrigger, 20L, mockWindowFunction);
  testHarness.open();
  when(mockTrigger.onElement(anyInt(), anyLong(), anyTimeWindow(), anyTriggerContext()))
    .thenReturn(TriggerResult.FIRE);
  when(mockAssigner.assignWindows(anyInt(), anyLong(), anyAssignerContext()))
    .thenReturn(Arrays.asList(new TimeWindow(0, 20)));
  doAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
      InternalWindowFunction.InternalWindowContext context = (InternalWindowFunction.InternalWindowContext) invocationOnMock.getArguments()[2];
      context.windowState().getState(valueStateDescriptor).update("hello");
      return null;
    }
  }).when(mockWindowFunction).process(anyInt(), anyTimeWindow(), anyInternalWindowContext(), anyIntIterable(), WindowOperatorContractTest.<Void>anyCollector());
  expectedException.expect(UnsupportedOperationException.class);
  expectedException.expectMessage("Per-window state is not allowed when using merging windows.");
  testHarness.processElement(new StreamRecord<>(0, 0L));
}

代码示例来源:origin: bumptech/glide

@Test(expected = CancellationException.class)
public void testThrowsCancellationExceptionIfCancelledWhileWaiting()
  throws ExecutionException, InterruptedException {
 doAnswer(
     new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocationOnMock) {
       future.cancel(false);
       return null;
      }
     })
   .when(waiter)
   .waitForTimeout(eq(future), anyLong());
 future.get();
}

代码示例来源:origin: bumptech/glide

@Test
public void testCallsSourceExecutorEngineIfOptionsIsSet() {
 doAnswer(new CallSizeReady(100, 100)).when(builder.target)
   .getSize(any(SizeReadyCallback.class));
 SingleRequest<List> request = builder
   .setUseUnlimitedSourceGeneratorsPool(false)
   .build();
 request.begin();
 verify(builder.engine)
   .load(
     eq(builder.glideContext),
     eq(builder.model),
     eq(builder.signature),
     anyInt(),
     anyInt(),
     eq(Object.class),
     eq(List.class),
     any(Priority.class),
     any(DiskCacheStrategy.class),
     eq(builder.transformations),
     anyBoolean(),
     anyBoolean(),
     any(Options.class),
     anyBoolean(),
     eq(false),
     /*useAnimationPool=*/ anyBoolean(),
     anyBoolean(),
     any(ResourceCallback.class),
     anyExecutor());
}

代码示例来源:origin: bumptech/glide

@Test
public void testCanReRunClearedRequests() {
 doAnswer(new CallSizeReady(100, 100)).when(builder.target)
   .getSize(any(SizeReadyCallback.class));
 when(builder.engine.load(
     eq(builder.glideContext),
     eq(builder.model),
     eq(Object.class),
     eq(List.class),
     any(Priority.class),
     any(DiskCacheStrategy.class),
     eq(builder.transformations),
     anyBoolean(),
 request.begin();
 verify(builder.target, times(2)).onResourceReady(eq(builder.result), anyTransition());

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

@Test
public void noExceptionThrownIfNoUserExceptionAndTimeoutDoesNotOccur() throws Throwable {
  doAnswer((Answer<Void>) invocation -> {
    return null;
  }).when(statement).evaluate();
  new SpringFailOnTimeout(statement, 100).evaluate();
}

代码示例来源:origin: bumptech/glide

@Before
public void setUp() throws UnsupportedEncodingException {
 MockitoAnnotations.initMocks(this);
 doAnswer(new WriteDigest("firstKey")).when(firstKey)
   .updateDiskCacheKey(any(MessageDigest.class));
 doAnswer(new WriteDigest("firstSignature")).when(firstSignature)
   .updateDiskCacheKey(any(MessageDigest.class));
 doAnswer(new WriteDigest("secondKey")).when(secondKey)
   .updateDiskCacheKey(any(MessageDigest.class));
 doAnswer(new WriteDigest("secondSignature")).when(secondSignature)
   .updateDiskCacheKey(any(MessageDigest.class));
}

代码示例来源:origin: bumptech/glide

@Before
public void setUp() {
 MockitoAnnotations.initMocks(this);
 doAnswer(new AddBitmapPoolAnswer(addedBitmaps)).when(pool).put(any(Bitmap.class));
 when(pool.getDirty(anyInt(), anyInt(), any(Bitmap.Config.class)))
   .thenAnswer(new CreateBitmap());
 when(cache.put(any(Key.class), anyResource()))
   .thenAnswer(new AddBitmapCacheAnswer(addedBitmaps));
}

代码示例来源:origin: MovingBlocks/Terasology

private static Chunk mockChunkWithReadinessStateAt(final int x, final int y, final int z) {
  final Chunk chunk = mockChunkAt(x, y, z);
  AtomicBoolean chunkReady = new AtomicBoolean();
  when(chunk.isReady()).thenAnswer(i -> chunkReady.get());
  doAnswer(i -> {
    chunkReady.set(true);
    return null;
  }).when(chunk).markReady();
  return chunk;
}

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

static ResultSet resultSetReturningMetadata(ResultSetMetaData metadata) throws SQLException {
  final ResultSet rs = mock(ResultSet.class);
  when(rs.getMetaData()).thenReturn(metadata);
  final AtomicInteger counter = new AtomicInteger(1);
  Mockito.doAnswer(new Answer<Boolean>() {
    @Override
    public Boolean answer(InvocationOnMock invocation) throws Throwable {
      return counter.getAndDecrement() > 0;
    }
  }).when(rs).next();
  return rs;
}

代码示例来源:origin: bumptech/glide

@Test
public void transform_withColorDrawable_andUnitBitmapTransformation_recycles() {
 bitmapPool = mock(BitmapPool.class);
 Glide.tearDown();
 Glide.init(context, new GlideBuilder().setBitmapPool(bitmapPool));
 when(
   bitmapTransformation
     .transform(
       any(Context.class), anyBitmapResource(), anyInt(), anyInt()))
   .thenAnswer(new ReturnGivenResource());
 final Resource<Drawable> input = new SimpleResource<Drawable>(colorDrawable);
 doAnswer(new Answer<Void>() {
  @Override
  public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
   return null;
 }).when(bitmapPool).put(any(Bitmap.class));
 when(bitmapPool.get(anyInt(), anyInt(), any(Bitmap.Config.class)))
   .thenAnswer(new Answer<Bitmap>() {
    @Override
 verify(bitmapPool).put(isA(Bitmap.class));

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

@Test
public void testOnElementPurgeDoesNotCleanupMergingSet() throws Exception {
  MergingWindowAssigner<Integer, TimeWindow> mockAssigner = mockMergingAssigner();
  Trigger<Integer, TimeWindow> mockTrigger = mockTrigger();
  InternalWindowFunction<Iterable<Integer>, Void, Integer, TimeWindow> mockWindowFunction = mockWindowFunction();
  KeyedOneInputStreamOperatorTestHarness<Integer, Integer, Void> testHarness =
      createWindowOperator(mockAssigner, mockTrigger, 0L, mockWindowFunction);
  testHarness.open();
  when(mockAssigner.assignWindows(anyInt(), anyLong(), anyAssignerContext()))
      .thenReturn(Arrays.asList(new TimeWindow(0, 2)));
  assertEquals(0, testHarness.getOutput().size());
  assertEquals(0, testHarness.numKeyedStateEntries());
  doAnswer(new Answer<TriggerResult>() {
    @Override
    public TriggerResult answer(InvocationOnMock invocation) throws Exception {
      return TriggerResult.PURGE;
    }
  }).when(mockTrigger).onElement(Matchers.<Integer>anyObject(), anyLong(), anyTimeWindow(), anyTriggerContext());
  testHarness.processElement(new StreamRecord<>(0, 0L));
  assertEquals(1, testHarness.numKeyedStateEntries()); // the merging window set
  assertEquals(1, testHarness.numEventTimeTimers()); // one cleanup timer
  assertEquals(0, testHarness.getOutput().size());
}

代码示例来源:origin: bumptech/glide

@Test(expected = InterruptedException.class)
public void testThrowsInterruptedExceptionIfThreadInterruptedWhenDoneWaiting()
  throws InterruptedException, ExecutionException {
 doAnswer(
     new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocationOnMock) {
       Thread.currentThread().interrupt();
       return null;
      }
     })
   .when(waiter)
   .waitForTimeout(eq(future), anyLong());
 future.get();
}

代码示例来源:origin: bumptech/glide

@Test
public void testCallsSourceUnlimitedExecutorEngineIfOptionsIsSet() {
 doAnswer(new CallSizeReady(100, 100)).when(builder.target)
   .getSize(any(SizeReadyCallback.class));
 SingleRequest<List> request = builder
   .setUseUnlimitedSourceGeneratorsPool(true)
   .build();
 request.begin();
 verify(builder.engine)
   .load(
     eq(builder.glideContext),
     eq(builder.model),
     eq(builder.signature),
     anyInt(),
     anyInt(),
     eq(Object.class),
     eq(List.class),
     any(Priority.class),
     any(DiskCacheStrategy.class),
     eq(builder.transformations),
     anyBoolean(),
     anyBoolean(),
     any(Options.class),
     anyBoolean(),
     eq(true),
     /*useAnimationPool=*/ anyBoolean(),
     anyBoolean(),
     any(ResourceCallback.class),
     anyExecutor());
}

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

@Test
public void timeoutExceptionThrownIfNoUserException() throws Throwable {
  doAnswer((Answer<Void>) invocation -> {
    TimeUnit.MILLISECONDS.sleep(50);
    return null;
  }).when(statement).evaluate();
  exception.expect(TimeoutException.class);
  new SpringFailOnTimeout(statement, 1).evaluate();
}

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

private static ExecutorService immediateExecutor()
{
  ExecutorService result = mock( ExecutorService.class );
  doAnswer( invocation ->
  {
    invocation.<Runnable>getArgument( 0 ).run();
    return null;
  } ).when( result ).execute( any( Runnable.class ) );
  return result;
}

代码示例来源:origin: bumptech/glide

@Before
public void setUp() {
 MockitoAnnotations.initMocks(this);
 context = RuntimeEnvironment.application;
 doAnswer(new Util.WriteDigest("first")).when(first)
   .updateDiskCacheKey(any(MessageDigest.class));
 doAnswer(new Util.WriteDigest("second")).when(second)
   .updateDiskCacheKey(any(MessageDigest.class));
}

相关文章

微信公众号

最新文章

更多