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

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

本文整理了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:

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

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

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

代码示例

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

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

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

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

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

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

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

  1. private NativeIndexPopulator<GenericKey,NativeIndexValue> failOnDropNativeIndexPopulator()
  2. {
  3. NativeIndexPopulator<GenericKey,NativeIndexValue> populator = mockNativeIndexPopulator();
  4. doThrow( CustomFailure.class ).when( populator ).drop();
  5. return populator;
  6. }

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

  1. @Test
  2. public void shouldAllExceptionsExceptionQuietly() throws Exception {
  3. doThrow(new IOException()).when(zipUtil).unzip(DownloadableFile.AGENT_PLUGINS.getLocalFile(), new File(SystemEnvironment.PLUGINS_PATH));
  4. try {
  5. doThrow(new RuntimeException("message")).when(pluginJarLocationMonitor).initialize();
  6. agentPluginsInitializer.onApplicationEvent(null);
  7. } catch (Exception e) {
  8. fail("should have handled IOException");
  9. }
  10. }
  11. }

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

  1. @Test(expected = IOException.class)
  2. public void testCloseThrowsIfWrappedStreamThrowsOnClose() throws IOException {
  3. InputStream wrapped = mock(InputStream.class);
  4. doThrow(new IOException()).when(wrapped).close();
  5. stream = new RecyclableBufferedInputStream(wrapped, byteArrayPool);
  6. stream.close();
  7. }

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

  1. private void setupFlushable(boolean shouldThrowOnFlush) throws IOException {
  2. mockFlushable = mock(Flushable.class);
  3. if (shouldThrowOnFlush) {
  4. doThrow(
  5. new IOException(
  6. "This should only appear in the " + "logs. It should not be rethrown."))
  7. .when(mockFlushable)
  8. .flush();
  9. }
  10. }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  1. @Test
  2. public void closeAllAndRethrowException() throws Exception
  3. {
  4. doThrow( new IOException( "Faulty closable" ) ).when( faultyClosable ).close();
  5. expectedException.expect( IOException.class );
  6. expectedException.expectMessage( "Exception closing multiple resources" );
  7. expectedException.expect( new NestedThrowableMatcher( IOException.class ) );
  8. IOUtils.closeAll( goodClosable1, faultyClosable, goodClosable2 );
  9. }

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

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

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

  1. @Test
  2. void shouldMoveToFailedOnRun_fail() throws Throwable
  3. {
  4. BoltStateMachineV3 machine = getBoltStateMachineInTxReadyState();
  5. // When
  6. BoltResponseHandler handler = mock( BoltResponseHandler.class );
  7. doThrow( new RuntimeException( "Error!" ) ).when( handler ).onRecords( any(), anyBoolean() );
  8. machine.process( new RunMessage( "A cypher query" ), handler );
  9. // Then
  10. assertThat( machine.state(), instanceOf( FailedState.class ) );
  11. }

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

  1. @Test
  2. public void shouldContinueWithBuildingPluginInfoIfPluginSettingsIsNotProvidedByPlugin() {
  3. GoPluginDescriptor descriptor = new GoPluginDescriptor("plugin1", null, null, null, null, false);
  4. doThrow(new RuntimeException("foo")).when(extension).getPluginSettingsConfiguration("plugin1");
  5. ArtifactPluginInfo artifactPluginInfo = new ArtifactPluginInfoBuilder(extension).pluginInfoFor(descriptor);
  6. assertThat(artifactPluginInfo.getDescriptor(), is(descriptor));
  7. assertThat(artifactPluginInfo.getExtensionName(), is(PluginConstants.ARTIFACT_EXTENSION));
  8. }
  9. }

相关文章

最新文章

更多