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

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

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

Mockito.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();

1.当你监视真实的对象时,你希望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: Netflix/zuul

@Test
  public void testFileManagerInit() throws Exception
  {
    FilterFileManagerConfig config = new FilterFileManagerConfig(new String[]{"test", "test1"}, new String[]{"com.netflix.blah.SomeFilter"}, 1);
    FilterFileManager manager = new FilterFileManager(config, filterLoader);
    manager = spy(manager);
    doNothing().when(manager).manageFiles();
    manager.init();
    verify(manager, atLeast(1)).manageFiles();
    verify(manager, times(1)).startPoller();
    assertNotNull(manager.poller);
  }
}

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

@Override
  public OutputCommitter getOutputCommitter(TaskAttemptContext context) throws IOException, InterruptedException {
    final OutputCommitter outputCommitter = Mockito.mock(OutputCommitter.class);
    doNothing().when(outputCommitter).setupJob(any(JobContext.class));
    return outputCommitter;
  }
}

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

@Test
public void shouldClearWorkingDirectoryBeforeCheckingOut() throws Exception {
  File workingDirectory = mock(File.class);
  when(workingDirectory.exists()).thenReturn(true);
  TfsSDKCommand spy = spy(tfsCommand);
  doNothing().when(spy).initializeWorkspace(workingDirectory);
  doNothing().when(spy).retrieveFiles(workingDirectory, null);
  spy.checkout(workingDirectory, null);
  verify(workingDirectory).exists();
}

代码示例来源:origin: SonarSource/sonarqube

private void mockMigrationDoesNothing() {
  doNothing().when(migrationEngine).execute();
 }
}

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

@Test
public void testCloseSocket() throws IOException {
 final Socket mockSocket = mock(Socket.class, "closeSocketTest");
 doNothing().when(mockSocket).close();
 assertThat(SocketUtils.close(mockSocket)).isTrue();
 verify(mockSocket, times(1)).close();
}

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

Putter( AtomicBoolean condition, DefaultFileSystemManager fsm ) {
 super( condition );
 this.fsm = fsm;
 provider = mock( AbstractFileProvider.class );
 doNothing().when( provider ).freeUnusedResources();
}

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

@Test
public void testCloseServerSocket() throws IOException {
 final ServerSocket mockServerSocket = mock(ServerSocket.class, "closeServerSocketTest");
 doNothing().when(mockServerSocket).close();
 assertThat(SocketUtils.close(mockServerSocket)).isTrue();
 verify(mockServerSocket, times(1)).close();
}

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

private OutputCommitter setupOutputCommitter(boolean needsTaskCommit) throws IOException {
  OutputCommitter outputCommitter = Mockito.mock(OutputCommitter.class);
  when(outputCommitter.needsTaskCommit(nullable(TaskAttemptContext.class))).thenReturn(needsTaskCommit);
  doNothing().when(outputCommitter).commitTask(any(TaskAttemptContext.class));
  return outputCommitter;
}

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

@Test
public void shouldCheckoutAllFilesWhenWorkingDirectoryIsDeleted() throws Exception {
  File workingDirectory = mock(File.class);
  when(workingDirectory.exists()).thenReturn(false);
  when(workingDirectory.getCanonicalPath()).thenReturn("canonical_path");
  when(workingDirectory.listFiles()).thenReturn(null);
  TfsSDKCommand spy = spy(tfsCommand);
  doNothing().when(spy).initializeWorkspace(workingDirectory);
  GoTfsWorkspace workspace = mock(GoTfsWorkspace.class);
  when(client.queryWorkspace(TFS_WORKSPACE, USERNAME)).thenReturn(workspace);
  doNothing().when(workspace).get(any(GetRequest.class), eq(GetOptions.GET_ALL));
  spy.checkout(workingDirectory, null);
  verify(workingDirectory).getCanonicalPath();
  verify(workingDirectory).listFiles();
  verify(workspace).get(any(GetRequest.class), eq(GetOptions.GET_ALL));
}

代码示例来源:origin: SonarSource/sonarqube

private static DbVersion newMockFailingOnSecondBuildCall() {
  DbVersion res = mock(DbVersion.class);
  doNothing()
   .doThrow(new RuntimeException("addStep should not be called twice"))
   .when(res)
   .addSteps(any(MigrationStepRegistry.class));
  return res;
 }
}

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

@Test
public void should_GetLatestRevisions_WhenCheckingOutToLaterRevision() throws Exception {
  File workingDirectory = mock(File.class);
  when(workingDirectory.exists()).thenReturn(false);
  when(workingDirectory.getCanonicalPath()).thenReturn("canonical_path");
  File[] checkedOutFiles = {mock(File.class)};
  when(workingDirectory.listFiles()).thenReturn(checkedOutFiles);
  TfsSDKCommand spy = spy(tfsCommand);
  doNothing().when(spy).initializeWorkspace(workingDirectory);
  GoTfsWorkspace workspace = mock(GoTfsWorkspace.class);
  when(client.queryWorkspace(TFS_WORKSPACE, USERNAME)).thenReturn(workspace);
  doNothing().when(workspace).get(any(GetRequest.class), eq(GetOptions.NONE));
  spy.checkout(workingDirectory, null);
  verify(workingDirectory).getCanonicalPath();
  verify(workingDirectory).listFiles();
  verify(workspace).get(any(GetRequest.class), eq(GetOptions.NONE));
}

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

private AgentBootstrapper stubJVMExit(AgentBootstrapper bootstrapper) {
  AgentBootstrapper spy = spy(bootstrapper);
  doNothing().when(spy).jvmExit(anyInt());
  return spy;
}

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

@Test
public void shouldMarkPluginAsInvalidWhenServiceReportsAnError() throws Exception {
  String pluginId = "plugin-id";
  String message = "plugin is broken beyond repair";
  List<String> reasons = Arrays.asList(message);
  doNothing().when(pluginRegistry).markPluginInvalid(pluginId, reasons);
  serviceDefault.reportErrorAndInvalidate(pluginId, reasons);
  verify(pluginRegistry).markPluginInvalid(pluginId, reasons);
}

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

@Before
public void setUpPluginRegistry() throws Exception {
 // Intercept access to registry
 registry = LifecycleSupport.registry = KettleLifecycleSupport.registry = mock( PluginRegistry.class );
 registeredPlugins = new ArrayList<PluginInterface>();
 when( registry.getPlugins( KettleLifecyclePluginType.class ) ).thenReturn( registeredPlugins );
 typeListenerRegistration = ArgumentCaptor.forClass( PluginTypeListener.class );
 doNothing().when( registry ).addPluginListener( eq( KettleLifecyclePluginType.class ), typeListenerRegistration.capture() );
}

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

@Test
public void destroyShouldCloseClientAndCollection() throws Exception {
  doNothing().when(client).close();
  doNothing().when(collection).close();
  tfsCommand.destroy();
  verify(client).close();
  verify(collection).close();
}

代码示例来源:origin: google/agera

@Before
public void setUp() {
 initMocks(this);
 sharedPreferenceListenerCaptor =
   ArgumentCaptor.forClass(OnSharedPreferenceChangeListener.class);
 doNothing().when(sharedPreferences).registerOnSharedPreferenceChangeListener(
   sharedPreferenceListenerCaptor.capture());
 updatable = mockUpdatable();
 secondUpdatable = mockUpdatable();
}

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

@Test
public void testCommit() throws Exception {
  Mockito.when(mockTuple.getSourceStreamId()).thenReturn("default");
  executor.execute(mockTuple);
  Mockito.when(mockCheckpointTuple.getSourceStreamId()).thenReturn(CheckpointSpout.CHECKPOINT_STREAM_ID);
  Mockito.when(mockCheckpointTuple.getValueByField(CHECKPOINT_FIELD_ACTION)).thenReturn(COMMIT);
  Mockito.when(mockCheckpointTuple.getLongByField(CHECKPOINT_FIELD_TXID)).thenReturn(new Long(0));
  Mockito.doNothing().when(mockOutputCollector).ack(mockCheckpointTuple);
  executor.execute(mockCheckpointTuple);
  Mockito.verify(mockBolt, Mockito.times(1)).preCommit(new Long(0));
  Mockito.verify(mockState, Mockito.times(1)).commit(new Long(0));
}

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

private void authorize(ResourcePermission.Resource resource,
  ResourcePermission.Operation operation, String region, String key) {
 doNothing().when(security).authorize(resource, operation, region, key);
 doNothing().when(security).authorize(new ResourcePermission(resource, operation, region, key));
}

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

@Test
public void testRollback() throws Exception {
  Mockito.when(mockTuple.getSourceStreamId()).thenReturn("default");
  executor.execute(mockTuple);
  Mockito.when(mockCheckpointTuple.getSourceStreamId()).thenReturn(CheckpointSpout.CHECKPOINT_STREAM_ID);
  Mockito.when(mockCheckpointTuple.getValueByField(CHECKPOINT_FIELD_ACTION)).thenReturn(ROLLBACK);
  Mockito.when(mockCheckpointTuple.getLongByField(CHECKPOINT_FIELD_TXID)).thenReturn(new Long(0));
  Mockito.doNothing().when(mockOutputCollector).ack(mockCheckpointTuple);
  executor.execute(mockCheckpointTuple);
  Mockito.verify(mockState, Mockito.times(1)).rollback();
}

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

private LocalFsBlobStore initLocalFs() {
 LocalFsBlobStore store = new LocalFsBlobStore();
 // Spy object that tries to mock the real object store
 LocalFsBlobStore spy = spy(store);
 Mockito.doNothing().when(spy).checkForBlobUpdate("test");
 Mockito.doNothing().when(spy).checkForBlobUpdate("other");
 Mockito.doNothing().when(spy).checkForBlobUpdate("test-empty-subject-WE");
 Mockito.doNothing().when(spy).checkForBlobUpdate("test-empty-subject-DEF");
 Mockito.doNothing().when(spy).checkForBlobUpdate("test-empty-acls");
 Map<String, Object> conf = Utils.readStormConfig();
 conf.put(Config.STORM_ZOOKEEPER_PORT, zk.getPort());
 conf.put(Config.STORM_LOCAL_DIR, baseFile.getAbsolutePath());
 conf.put(Config.STORM_PRINCIPAL_TO_LOCAL_PLUGIN,"org.apache.storm.security.auth.DefaultPrincipalToLocal");
 NimbusInfo nimbusInfo = new NimbusInfo("localhost", 0, false);
 spy.prepare(conf, null, nimbusInfo, null);
 return spy;
}

相关文章