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

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

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

Mockito.doThrow介绍

[英]Use doThrow() when you want to stub the void method to throw exception of specified class.

A new exception instance will be created for each method invocation.

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

Example:

doThrow(RuntimeException.class).when(mock).someVoidMethod();

[中]如果要存根void方法以引发指定类的异常,请使用doThrow()
将为每个方法调用创建一个新的异常实例。
stubing void需要与Mockito#when(Object)不同的方法,因为编译器不喜欢括号内的void方法。。。
例子:

doThrow(RuntimeException.class).when(mock).someVoidMethod();

代码示例

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

private void setupCloseable(boolean shouldThrow) throws IOException {
 mockCloseable = mock(Closeable.class);
 if (shouldThrow) {
  doThrow(new IOException("This should only appear in the logs. It should not be rethrown."))
    .when(mockCloseable)
    .close();
 }
}

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

@Test
public void testHandlesExceptionOnClose() throws Exception {
 fetcher.loadData(Priority.NORMAL, callback);
 doThrow(new IOException("Test")).when(fetcher.closeable).close();
 fetcher.cleanup();
 verify(fetcher.closeable).close();
}

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

@Test
public void shouldNotInitializeServerIfSettingIsTurnedOff() throws Exception {
  when(systemEnvironment.getAgentStatusEnabled()).thenReturn(true);
  AgentStatusHttpd spy = spy(agentStatusHttpd);
  doThrow(new RuntimeException("This is not expected to be invoked")).when(spy).start();
  spy.init();
}

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

private NativeIndexPopulator<GenericKey,NativeIndexValue> failOnDropNativeIndexPopulator()
{
  NativeIndexPopulator<GenericKey,NativeIndexValue> populator = mockNativeIndexPopulator();
  doThrow( CustomFailure.class ).when( populator ).drop();
  return populator;
}

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

@Test
  public void shouldAllExceptionsExceptionQuietly() throws Exception {
    doThrow(new IOException()).when(zipUtil).unzip(DownloadableFile.AGENT_PLUGINS.getLocalFile(), new File(SystemEnvironment.PLUGINS_PATH));
    try {
      doThrow(new RuntimeException("message")).when(pluginJarLocationMonitor).initialize();
      agentPluginsInitializer.onApplicationEvent(null);
    } catch (Exception e) {
      fail("should have handled IOException");
    }
  }
}

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

@Test(expected = IOException.class)
public void testCloseThrowsIfWrappedStreamThrowsOnClose() throws IOException {
 InputStream wrapped = mock(InputStream.class);
 doThrow(new IOException()).when(wrapped).close();
 stream = new RecyclableBufferedInputStream(wrapped, byteArrayPool);
 stream.close();
}

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

private void setupFlushable(boolean shouldThrowOnFlush) throws IOException {
 mockFlushable = mock(Flushable.class);
 if (shouldThrowOnFlush) {
  doThrow(
      new IOException(
        "This should only appear in the " + "logs. It should not be rethrown."))
    .when(mockFlushable)
    .flush();
 }
}

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

@Test
void shouldGiveAClearErrorIfTheArchiveAlreadyExists() throws Exception
{
  doThrow( new FileAlreadyExistsException( "the-archive-path" ) ).when( dumper ).dump( any(), any(), any(), any() );
  CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( "foo.db" ) );
  assertEquals( "archive already exists: the-archive-path", commandFailed.getMessage() );
}

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

@Test
public void userExceptionPropagates() throws Throwable {
  doThrow(new Boom()).when(statement).evaluate();
  exception.expect(Boom.class);
  new SpringFailOnTimeout(statement, 1).evaluate();
}

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

@Test
public void should_not_fail_on_statement_errors() throws SQLException {
 Statement statement = mock(Statement.class);
 doThrow(new SQLException()).when(statement).close();
 DatabaseUtils.closeQuietly(statement);
 // no failure
 verify(statement).close(); // just to be sure
}

代码示例来源:origin: AsyncHttpClient/async-http-client

@Test
public void testOnBodyPartReceivedWithResumableListenerThrowsException() throws Exception {
 ResumableAsyncHandler handler = new ResumableAsyncHandler();
 ResumableListener resumableListener = mock(ResumableListener.class);
 doThrow(new IOException()).when(resumableListener).onBytesReceived(any());
 handler.setResumableListener(resumableListener);
 HttpResponseBodyPart bodyPart = mock(HttpResponseBodyPart.class);
 State state = handler.onBodyPartReceived(bodyPart);
 assertEquals(state, AsyncHandler.State.ABORT,
     "State should be ABORT if the resumableListener threw an exception in onBodyPartReceived");
}

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

@Test
void shouldGiveAClearMessageIfTheArchiveDoesntExist() throws IOException, IncorrectFormat
{
  doThrow( new NoSuchFileException( archive.toString() ) ).when( loader ).load( any(), any(), any() );
  CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( null ) );
  assertEquals( "archive does not exist: " + archive, commandFailed.getMessage() );
}

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

@Test
public void shouldReturnErrorResponseWhenFailedToUploadFile() throws Exception {
  when(systemEnvironment.get(PLUGIN_EXTERNAL_PROVIDED_PATH)).thenReturn(EXTERNAL_DIRECTORY_PATH);
  doThrow(new IOException()).when(goFileSystem).copyFile(any(File.class), any(File.class));
  PluginUploadResponse response = pluginWriter.addPlugin(srcFile, srcFile.getName());
  assertFalse(response.isSuccess());
  assertTrue(response.errors().containsKey(HttpStatus.SC_INTERNAL_SERVER_ERROR));
}

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

@Test
public void should_not_fail_on_connection_errors() throws SQLException {
 Connection connection = mock(Connection.class);
 doThrow(new SQLException()).when(connection).close();
 DatabaseUtils.closeQuietly(connection);
 // no failure
 verify(connection).close(); // just to be sure
}

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

private static TransactionToApply newTransactionThatFailsWith( Exception error ) throws IOException
{
  TransactionRepresentation transaction = mock( TransactionRepresentation.class );
  when( transaction.additionalHeader() ).thenReturn( new byte[0] );
  // allow to build validated index updates but fail on actual tx application
  doThrow( error ).when( transaction ).accept( any() );
  long txId = ThreadLocalRandom.current().nextLong( 0, 1000 );
  TransactionToApply txToApply = new TransactionToApply( transaction );
  FakeCommitment commitment = new FakeCommitment( txId, mock( TransactionIdStore.class ) );
  commitment.setHasExplicitIndexChanges( false );
  txToApply.commitment( commitment, txId );
  return txToApply;
}

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

@Test
void shouldWrapIOExceptionsCarefullyBecauseCriticalInformationIsOftenEncodedInTheirNameButMissingFromTheirMessage()
    throws IOException, IncorrectFormat
{
  doThrow( new FileSystemException( "the-message" ) ).when( loader ).load( any(), any(), any() );
  CommandFailed commandFailed = assertThrows( CommandFailed.class, () -> execute( null ) );
  assertEquals( "unable to load database: FileSystemException: the-message", commandFailed.getMessage() );
}

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

@Test
public void closeAllAndRethrowException() throws Exception
{
  doThrow( new IOException( "Faulty closable" ) ).when( faultyClosable ).close();
  expectedException.expect( IOException.class );
  expectedException.expectMessage( "Exception closing multiple resources" );
  expectedException.expect( new NestedThrowableMatcher( IOException.class ) );
  IOUtils.closeAll( goodClosable1, faultyClosable, goodClosable2 );
}

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

@Test
public void should_not_fail_on_resulset_errors() throws SQLException {
 ResultSet rs = mock(ResultSet.class);
 doThrow(new SQLException()).when(rs).close();
 DatabaseUtils.closeQuietly(rs);
 // no failure
 verify(rs).close(); // just to be sure
}

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

@Test
void shouldMoveToFailedOnRun_fail() throws Throwable
{
  BoltStateMachineV3 machine = getBoltStateMachineInTxReadyState();
  // When
  BoltResponseHandler handler = mock( BoltResponseHandler.class );
  doThrow( new RuntimeException( "Error!" ) ).when( handler ).onRecords( any(), anyBoolean() );
  machine.process( new RunMessage( "A cypher query" ), handler );
  // Then
  assertThat( machine.state(), instanceOf( FailedState.class ) );
}

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

@Test
  public void shouldContinueWithBuildingPluginInfoIfPluginSettingsIsNotProvidedByPlugin() {
    GoPluginDescriptor descriptor = new GoPluginDescriptor("plugin1", null, null, null, null, false);
    doThrow(new RuntimeException("foo")).when(extension).getPluginSettingsConfiguration("plugin1");

    ArtifactPluginInfo artifactPluginInfo = new ArtifactPluginInfoBuilder(extension).pluginInfoFor(descriptor);

    assertThat(artifactPluginInfo.getDescriptor(), is(descriptor));
    assertThat(artifactPluginInfo.getExtensionName(), is(PluginConstants.ARTIFACT_EXTENSION));
  }
}

相关文章