org.powermock.api.mockito.PowerMockito.doNothing()方法的使用及代码示例

x33g5p2x  于2022-01-26 转载在 其他  
字(16.8k)|赞(0)|评价(0)|浏览(267)

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

PowerMockito.doNothing介绍

[英]Use doNothing() for setting void methods to do nothing. Beware that void methods on mocks do nothing by default! However, there are rare situations when doNothing() comes handy:

  1. Stubbing consecutive calls on a void method:
doNothing().doThrow(new RuntimeException()).when(mock).someVoidMethod(); 
//does nothing the first time: 
mock.someVoidMethod(); 
//throws RuntimeException the next time: 
mock.someVoidMethod();
  1. When you spy real objects and you want the void method to do nothing:
List list = new LinkedList(); 
List spy = spy(list); 
//let's make clear() do nothing 
doNothing().when(spy).clear(); 
spy.add("one"); 
//clear() does nothing, so the list still contains "one" 
spy.clear();

See examples in javadoc for Mockito class
[中]使用doNothing()将void方法设置为不执行任何操作。注意,mock上的void方法在默认情况下不起任何作用!然而,很少有情况下doNothing()会派上用场:
1.在void方法上存根连续调用:

doNothing().doThrow(new RuntimeException()).when(mock).someVoidMethod(); 
//does nothing the first time: 
mock.someVoidMethod(); 
//throws RuntimeException the next time: 
mock.someVoidMethod();

2.当你侦查真实的物体,你想让void方法什么都不做:

List list = new LinkedList(); 
List spy = spy(list); 
//let's make clear() do nothing 
doNothing().when(spy).clear(); 
spy.add("one"); 
//clear() does nothing, so the list still contains "one" 
spy.clear();

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

代码示例

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

@Test
public void testCloseAndFlushOutputStreamAfterCreatingHashCode() throws IOException {
  mockStatic(Closeables.class);
  doNothing().when(Closeables.class);
  Closeables.close(any(ObjectOutputStream.class), ArgumentMatchers.eq(false));
  mockStatic(Flushables.class);
  doNothing().when(Flushables.class);
  Flushables.flush(any(ObjectOutputStream.class), ArgumentMatchers.eq(false));
  final Configuration config = new DefaultConfiguration("myName");
  final PropertyCacheFile cache = new PropertyCacheFile(config, "fileDoesNotExist.txt");
  cache.load();
  verifyStatic(Closeables.class, times(1));
  Closeables.close(any(ObjectOutputStream.class), ArgumentMatchers.eq(false));
  verifyStatic(Flushables.class, times(1));
  Flushables.flush(any(ObjectOutputStream.class), ArgumentMatchers.eq(false));
}

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

@Test
public void testFlushAndCloseCacheFileOutputStream() throws IOException {
  mockStatic(Closeables.class);
  doNothing().when(Closeables.class);
  Closeables.close(any(OutputStream.class), ArgumentMatchers.eq(false));
  mockStatic(Flushables.class);
  doNothing().when(Flushables.class);
  Flushables.flush(any(OutputStream.class), ArgumentMatchers.eq(false));
  final Configuration config = new DefaultConfiguration("myName");
  final PropertyCacheFile cache = new PropertyCacheFile(config,
    temporaryFolder.newFile().getPath());
  cache.put("CheckedFileName.java", System.currentTimeMillis());
  cache.persist();
  verifyStatic(Closeables.class, times(1));
  Closeables.close(any(OutputStream.class), ArgumentMatchers.eq(false));
  verifyStatic(Flushables.class, times(1));
  Flushables.flush(any(OutputStream.class), ArgumentMatchers.eq(false));
}

代码示例来源:origin: facebook/stetho

@Test
public void testSkipFew() throws IOException {
 long numBytesToSkip = TEST_RESPONSE_BODY.length / 2;
 long result = mResponseHandlingInputStream.skip(numBytesToSkip);
 assertEquals(numBytesToSkip, result);
 assertBufferMatchesResponseBody(mTestOutputStream.toByteArray(), (int) numBytesToSkip);
 PowerMockito.mockStatic(CLog.class);
 PowerMockito.doNothing().when(CLog.class);
 CLog.writeToConsole(
   Mockito.any(ChromePeerManager.class),
   Mockito.any(Console.MessageLevel.class),
   Mockito.any(Console.MessageSource.class),
   Mockito.anyString());
 mResponseHandlingInputStream.close();
 PowerMockito.verifyStatic();
}

代码示例来源:origin: facebook/stetho

@Test
public void testReadOneByte() throws IOException {
 int result = mResponseHandlingInputStream.read();
 assertEquals(TEST_RESPONSE_BODY[0], positionToByte(result));
 assertBufferMatchesResponseBody(mTestOutputStream.toByteArray(), 1);
 PowerMockito.mockStatic(CLog.class);
 PowerMockito.doNothing().when(CLog.class);
 CLog.writeToConsole(
   Mockito.any(ChromePeerManager.class),
   Mockito.any(Console.MessageLevel.class),
   Mockito.any(Console.MessageSource.class),
   Mockito.anyString());
 mResponseHandlingInputStream.close();
 PowerMockito.verifyStatic();
}

代码示例来源:origin: Alluxio/alluxio

@Before
public void before() throws Exception {
 mContext = PowerMockito.mock(FileSystemContext.class);
 mAddress = mock(WorkerNetAddress.class);
 mClient = mock(BlockWorkerClient.class);
 mRequestObserver = mock(ClientCallStreamObserver.class);
 PowerMockito.when(mContext.acquireBlockWorkerClient(mAddress)).thenReturn(mClient);
 PowerMockito.when(mContext.getClientContext())
   .thenReturn(ClientContext.create(mConf));
 PowerMockito.when(mContext.getConf()).thenReturn(mConf);
 PowerMockito.doNothing().when(mContext).releaseBlockWorkerClient(mAddress, mClient);
 PowerMockito.when(mClient.writeBlock(any(StreamObserver.class))).thenReturn(mRequestObserver);
 PowerMockito.when(mRequestObserver.isReady()).thenReturn(true);
}

代码示例来源:origin: Alluxio/alluxio

@Before
public void before() throws Exception {
 mClientContext = ClientContext.create(mConf);
 mContext = PowerMockito.mock(FileSystemContext.class);
 mAddress = Mockito.mock(WorkerNetAddress.class);
 mClient = mock(BlockWorkerClient.class);
 mRequestObserver = mock(ClientCallStreamObserver.class);
 PowerMockito.when(mContext.getClientContext()).thenReturn(mClientContext);
 PowerMockito.when(mContext.getConf()).thenReturn(mConf);
 PowerMockito.when(mContext.acquireBlockWorkerClient(mAddress)).thenReturn(mClient);
 PowerMockito.doNothing().when(mContext).releaseBlockWorkerClient(mAddress, mClient);
 PowerMockito.when(mClient.writeBlock(any(StreamObserver.class))).thenReturn(mRequestObserver);
 PowerMockito.when(mRequestObserver.isReady()).thenReturn(true);
}

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

@Test
public void releaseEntryShouldSetValueToRemovePhase2AndSetsAsyncToFalseForDiskEntry() {
 // mock region entry
 OffHeapRegionEntry re = mock(VersionedStatsDiskRegionEntryOffHeap.class);
 when(re.getAddress()).thenReturn(1L);
 when(re.setAddress(1L, OffHeapRegionEntryHelper.REMOVED_PHASE2_ADDRESS))
   .thenReturn(Boolean.TRUE);
 DiskId spy = Mockito.spy(DiskId.class);
 when(((DiskEntry) re).getDiskId()).thenReturn(spy);
 when(spy.isPendingAsync()).thenReturn(Boolean.TRUE);
 // mock required methods
 PowerMockito.spy(OffHeapRegionEntryHelper.class);
 PowerMockito.doNothing().when(OffHeapRegionEntryHelper.class);
 OffHeapRegionEntryHelper.setValue(re, Token.REMOVED_PHASE2);
 OffHeapRegionEntryHelper.releaseEntry(re);
 verify(spy, times(1)).setPendingAsync(Boolean.FALSE);
 PowerMockito.verifyStatic(OffHeapRegionEntryHelper.class);
 OffHeapRegionEntryHelper.setValue(re, Token.REMOVED_PHASE2);
}

代码示例来源:origin: facebook/stetho

@Test
public void testReadPartial() throws IOException {
 int numBytesToRead = TEST_RESPONSE_BODY.length / 2;
 byte[] tempReadingBuffer = new byte[numBytesToRead];
 int result = mResponseHandlingInputStream.read(tempReadingBuffer, 0, numBytesToRead);
 assertEquals(numBytesToRead, result);
 assertBufferMatchesResponseBody(tempReadingBuffer, numBytesToRead);
 assertBufferMatchesResponseBody(mTestOutputStream.toByteArray(), numBytesToRead);
 PowerMockito.mockStatic(CLog.class);
 PowerMockito.doNothing().when(CLog.class);
 CLog.writeToConsole(
   Mockito.any(ChromePeerManager.class),
   Mockito.any(Console.MessageLevel.class),
   Mockito.any(Console.MessageSource.class),
   Mockito.anyString());
 mResponseHandlingInputStream.close();
 PowerMockito.verifyStatic();
}

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

@Test
public void releaseEntryShouldSetValueToRemovePhase2() {
 // mock region entry
 OffHeapRegionEntry re = mock(OffHeapRegionEntry.class);
 when(re.getAddress()).thenReturn(1L);
 when(re.setAddress(1L, OffHeapRegionEntryHelper.REMOVED_PHASE2_ADDRESS))
   .thenReturn(Boolean.TRUE);
 // mock required methods
 PowerMockito.spy(OffHeapRegionEntryHelper.class);
 PowerMockito.doNothing().when(OffHeapRegionEntryHelper.class);
 OffHeapRegionEntryHelper.setValue(re, Token.REMOVED_PHASE2);
 OffHeapRegionEntryHelper.releaseEntry(re);
 PowerMockito.verifyStatic(OffHeapRegionEntryHelper.class);
 OffHeapRegionEntryHelper.setValue(re, Token.REMOVED_PHASE2);
}

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

@Test
public void setValueShouldChangeTheRegionEntryAddressToNewAddressAndDoesNothingIfOldAddressIsATokenAddress() {
 // mock region entry
 OffHeapRegionEntry re = mock(OffHeapRegionEntry.class);
 long oldAddress = OffHeapRegionEntryHelper.REMOVED_PHASE1_ADDRESS;
 Token newValue = Token.REMOVED_PHASE2;
 long newAddress = OffHeapRegionEntryHelper.REMOVED_PHASE2_ADDRESS;
 // mock Chunk static methods - in-order to verify that release is never called
 PowerMockito.spy(OffHeapStoredObject.class);
 PowerMockito.doNothing().when(OffHeapStoredObject.class);
 OffHeapStoredObject.release(oldAddress);
 // mock region entry methods required for test
 when(re.getAddress()).thenReturn(oldAddress);
 when(re.setAddress(oldAddress, newAddress)).thenReturn(Boolean.TRUE);
 // invoke the method under test
 OffHeapRegionEntryHelper.setValue(re, newValue);
 // verify oldAddress is changed to newAddress
 verify(re, times(1)).setAddress(oldAddress, newAddress);
 // verify that release is never called as the old address is not on offheap
 PowerMockito.verifyStatic(OffHeapStoredObject.class, never());
 OffHeapStoredObject.release(oldAddress);
}

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

@Test
public void setValueShouldChangeTheRegionEntryAddressToNewAddressAndDoesNothingIfOldAddressIsAnEncodedAddress() {
 // mock region entry
 OffHeapRegionEntry re = mock(OffHeapRegionEntry.class);
 byte[] oldData =
   ByteBuffer.allocate(Integer.SIZE / Byte.SIZE).putInt((Integer) Integer.MAX_VALUE).array();
 long oldAddress = OffHeapRegionEntryHelper.encodeDataAsAddress(oldData, false, false);
 byte[] newData = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE)
   .putInt((Integer) Integer.MAX_VALUE - 1).array();
 TinyStoredObject newAddress =
   new TinyStoredObject(OffHeapRegionEntryHelper.encodeDataAsAddress(newData, false, false));
 // mock Chunk static methods - in-order to verify that release is never called
 PowerMockito.spy(OffHeapStoredObject.class);
 PowerMockito.doNothing().when(OffHeapStoredObject.class);
 OffHeapStoredObject.release(oldAddress);
 // mock region entry methods required for test
 when(re.getAddress()).thenReturn(oldAddress);
 when(re.setAddress(oldAddress, newAddress.getAddress())).thenReturn(Boolean.TRUE);
 // invoke the method under test
 OffHeapRegionEntryHelper.setValue(re, newAddress);
 // verify oldAddress is changed to newAddress
 verify(re, times(1)).setAddress(oldAddress, newAddress.getAddress());
 // verify that release is never called as the old address is not on offheap
 PowerMockito.verifyStatic(OffHeapStoredObject.class, never());
 OffHeapStoredObject.release(oldAddress);
}

代码示例来源:origin: Alluxio/alluxio

@Before
public void before() throws Exception {
 mContext = PowerMockito.mock(FileSystemContext.class);
 when(mContext.getClientContext())
   .thenReturn(ClientContext.create(ConfigurationTestUtils.defaults()));
 when(mContext.getConf()).thenReturn(ConfigurationTestUtils.defaults());
 mAddress = mock(WorkerNetAddress.class);
 ReadRequest readRequest =
   ReadRequest.newBuilder().setBlockId(BLOCK_ID).setChunkSize(CHUNK_SIZE).build();
 mFactory = new GrpcDataReader.Factory(mContext, mAddress, readRequest);
 mClient = mock(BlockWorkerClient.class);
 mRequestObserver = mock(ClientCallStreamObserver.class);
 when(mContext.acquireBlockWorkerClient(mAddress)).thenReturn(mClient);
 PowerMockito.doNothing().when(mContext).releaseBlockWorkerClient(mAddress, mClient);
 when(mClient.readBlock(any(StreamObserver.class))).thenReturn(mRequestObserver);
 when(mRequestObserver.isReady()).thenReturn(true);
}

代码示例来源:origin: Alluxio/alluxio

@Before
public void before() throws Exception {
 BlockWorkerClient workerClient = PowerMockito.mock(BlockWorkerClient.class);
 ClientCallStreamObserver requestObserver = PowerMockito.mock(ClientCallStreamObserver.class);
 when(requestObserver.isReady()).thenReturn(true);
 when(workerClient.openLocalBlock(any(StreamObserver.class)))
   .thenAnswer(new Answer() {
    public Object answer(InvocationOnMock invocation) {
     StreamObserver<OpenLocalBlockResponse> observer =
       invocation.getArgumentAt(0, StreamObserver.class);
     observer.onNext(OpenLocalBlockResponse.newBuilder().setPath("/tmp").build());
     observer.onCompleted();
     return requestObserver;
    }
   });
 mMockContext = PowerMockito.mock(FileSystemContext.class);
 PowerMockito.when(mMockContext.acquireBlockWorkerClient(Matchers.any(WorkerNetAddress.class)))
   .thenReturn(workerClient);
 PowerMockito.when(mMockContext.getClientContext()).thenReturn(ClientContext.create(mConf));
 PowerMockito.when(mMockContext.getConf()).thenReturn(mConf);
 PowerMockito.doNothing().when(mMockContext)
   .releaseBlockWorkerClient(Matchers.any(WorkerNetAddress.class),
     Matchers.any(BlockWorkerClient.class));
 mInfo = new BlockInfo().setBlockId(1);
 mOptions = new InStreamOptions(new URIStatus(new FileInfo().setBlockIds(Collections
   .singletonList(1L))), mConf);
}

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

@Test
public void setValueShouldChangeTheRegionEntryAddressToNewAddressAndReleaseOldValueIfItsOnOffHeap() {
 // mock region entry
 OffHeapRegionEntry re = mock(OffHeapRegionEntry.class);
 OffHeapStoredObject oldValue = createChunk(Long.MAX_VALUE);
 OffHeapStoredObject newValue = createChunk(Long.MAX_VALUE - 1);
 // mock Chunk static methods - in-order to verify that release is called
 PowerMockito.spy(OffHeapStoredObject.class);
 PowerMockito.doNothing().when(OffHeapStoredObject.class);
 OffHeapStoredObject.release(oldValue.getAddress());
 // mock region entry methods required for test
 when(re.getAddress()).thenReturn(oldValue.getAddress());
 when(re.setAddress(oldValue.getAddress(), newValue.getAddress())).thenReturn(Boolean.TRUE);
 // invoke the method under test
 OffHeapRegionEntryHelper.setValue(re, newValue);
 // verify oldAddress is changed to newAddress
 verify(re, times(1)).setAddress(oldValue.getAddress(), newValue.getAddress());
 // verify oldAddress is released
 PowerMockito.verifyStatic(OffHeapStoredObject.class);
 OffHeapStoredObject.release(oldValue.getAddress());
}

代码示例来源:origin: julian-klode/dns66

@Test
public void testFinishWrite_renameFailure() throws Exception {
  doCallRealMethod().when(reader).finishWrite(any(FileOutputStream.class));
  doNothing().when(reader).failWrite(any(FileOutputStream.class));
  when(workFile.renameTo(activeFile)).thenReturn(false);
  try {
    reader.finishWrite(fos);
    Mockito.verify(fos).close();
    Mockito.verify(reader).failWrite(fos);
    fail("Failing rename should fail finish");
  } catch (IOException e) {
    assertTrue(e.getMessage() + "wrong", e.getMessage().contains("Cannot commit"));
  }
}

代码示例来源:origin: julian-klode/dns66

@Test
public void testFinishWrite_closeFailure() throws Exception {
  doCallRealMethod().when(reader).finishWrite(any(FileOutputStream.class));
  doNothing().when(reader).failWrite(any(FileOutputStream.class));
  doThrow(new IOException("Not closing")).when(fos).close();
  when(workFile.renameTo(activeFile)).thenReturn(true);
  try {
    reader.finishWrite(fos);
    Mockito.verify(fos).close();
    Mockito.verify(reader).failWrite(fos);
    fail("Failing close should fail finish");
  } catch (IOException e) {
    assertTrue(e.getMessage() + "wrong", e.getMessage().contains("Not closing"));
  }
}

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

@Test
public void canEndTheSshConnectionTest() throws Exception {
  PowerMockito.spy(SshHelper.class);
  Session mockedSession = Mockito.mock(Session.class);
  PowerMockito.doReturn(true).when(SshHelper.class, "isChannelConditionEof", Mockito.anyInt());
  Mockito.when(mockedSession.waitForCondition(ChannelCondition.EXIT_STATUS, 1l)).thenReturn(0);
  PowerMockito.doNothing().when(SshHelper.class, "throwSshExceptionIfConditionsTimeout", Mockito.anyInt());
  SshHelper.canEndTheSshConnection(1, mockedSession, 0);
  PowerMockito.verifyStatic();
  SshHelper.isChannelConditionEof(Mockito.anyInt());
  SshHelper.throwSshExceptionIfConditionsTimeout(Mockito.anyInt());
  Mockito.verify(mockedSession).waitForCondition(ChannelCondition.EXIT_STATUS, 1l);
}

代码示例来源:origin: julian-klode/dns66

@Test
public void testHandleTimeout() throws Exception {
  doNothing().when(watchdog, "sendPacket");
  assertEquals(1000, watchdog.getPollTimeout());
  // Successful case increments
  watchdog.handleTimeout();
  assertEquals(4 * 1000, watchdog.getPollTimeout());
  watchdog.handleTimeout();
  assertEquals(4 * 4 * 1000, watchdog.getPollTimeout());
  watchdog.handleTimeout();
  watchdog.pollTimeout = 4 * 4 * 4 * 4 * 4 * 4 * 1000;
  watchdog.handleTimeout();
  assertEquals(4 * 4 * 4 * 4 * 4 * 4 * 1000, watchdog.getPollTimeout());
}

代码示例来源:origin: braintree/braintree_android

@Before
public void setup() {
  mActivity = spy(Robolectric.setupActivity(FragmentTestActivity.class));
  doNothing().when(mActivity).startActivity(any(Intent.class));
  AnalyticsDatabaseTestUtils.clearAllEvents(mActivity);
  mCalled = new AtomicBoolean(false);
}

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

@Test
@Features({"issues/219"})
public void testConnectWithDelay() throws Exception {
  ConnectionsRegistry.INSTANCE.setSocketAddressStatus("localhost", 123, 10);
  doNothing().when(SnifferSocketImpl.class, "sleepImpl", anyInt());
  sniffySocket.connect("localhost", 123);
  verifyPrivate(SnifferSocketImpl.class).invoke("sleepImpl", eq(10));
  verifyPrivate(delegate).invoke("connect", "localhost", 123);
  verifyNoMoreInteractions(delegate);
}

相关文章