public BDDStubber will(Answer<?> answer) { return new BDDStubberImpl(mockitoStubber.doAnswer(answer)); }
@Override public Stubber doAnswer(Answer answer) { return stubber().doAnswer(answer); }
public BDDStubber willAnswer(Answer<?> answer) { return new BDDStubberImpl(mockitoStubber.doAnswer(answer)); }
public BDDStubber willAnswer(Answer answer) { return new BDDStubberImpl(mockitoStubber.doAnswer(answer)); }
/** * Use <code>doAnswer()</code> when you want to stub a void method with generic {@link Answer}. * <p> * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets... * <p> * Example: * * <pre class="code"><code class="java"> * doAnswer(new Answer() { * public Object answer(InvocationOnMock invocation) { * Object[] args = invocation.getArguments(); * Mock mock = invocation.getMock(); * return null; * }}) * .when(mock).someMethod(); * </code></pre> * <p> * See examples in javadoc for {@link Mockito} class * * @param answer to answer when the stubbed method is called * @return stubber - to select a method for stubbing */ @CheckReturnValue public static Stubber doAnswer(Answer answer) { return MOCKITO_CORE.stubber().doAnswer(answer); }
@Test public void readAsynchronousFileChannelError() throws Exception { AsynchronousFileChannel channel = mock(AsynchronousFileChannel.class); doAnswer(invocation -> { ByteBuffer byteBuffer = invocation.getArgument(0); byteBuffer.put("foo".getBytes(StandardCharsets.UTF_8)); byteBuffer.flip(); long pos = invocation.getArgument(1); assertEquals(0, pos); DataBuffer dataBuffer = invocation.getArgument(2); CompletionHandler<Integer, DataBuffer> completionHandler = invocation.getArgument(3); completionHandler.completed(3, dataBuffer); return null; }).doAnswer(invocation -> { DataBuffer dataBuffer = invocation.getArgument(2); CompletionHandler<Integer, DataBuffer> completionHandler = invocation.getArgument(3); completionHandler.failed(new IOException(), dataBuffer); return null; }) .when(channel).read(any(), anyLong(), any(), any()); Flux<DataBuffer> result = DataBufferUtils.readAsynchronousFileChannel(() -> channel, this.bufferFactory, 3); StepVerifier.create(result) .consumeNextWith(stringConsumer("foo")) .expectError(IOException.class) .verify(Duration.ofSeconds(3)); }
@Test public void testIntermittentRuntimeExceptions() throws Exception { setUp(); FileSystem spyfs = Mockito.spy(fs); Mockito.doThrow(new RuntimeException()) .doAnswer(Mockito.CALLS_REAL_METHODS) .when(spyfs) .open(source); byte[] actualCheckSum = copyFileWithCheckSumTest(fetcher, spyfs, source, copyLocation, stats, CheckSumType.MD5, buffer); assertEquals(Arrays.equals(actualCheckSum, checksumCalculated), true); }
@Test public void testIOExceptionIntermittent() throws Exception { setUp(); FileSystem spyfs = Mockito.spy(fs); Mockito.doThrow(new IOException()) .doAnswer(Mockito.CALLS_REAL_METHODS) .when(spyfs) .open(source); byte[] actualCheckSum = copyFileWithCheckSumTest(fetcher, spyfs, source, copyLocation, stats, CheckSumType.MD5, buffer); assertEquals(Arrays.equals(actualCheckSum, checksumCalculated), true); }
@Test public void testReadExceedsBuffer() throws IOException { int bufferSize = RESPONSE.length() / 3; unixDomainSocket = new UnixDomainSocket(reader, writer, RESPONSE.length() / 3); doAnswer(invocation -> { Object[] args = invocation.getArguments(); ((CharBuffer) args[0]).append(RESPONSE.substring(0, bufferSize)); return RESPONSE.length(); }) .doAnswer(invocation -> { Object[] args = invocation.getArguments(); ((CharBuffer) args[0]).append( RESPONSE.substring(bufferSize, bufferSize * 2)); return RESPONSE.length(); }).doAnswer(invocation -> { Object[] args = invocation.getArguments(); ((CharBuffer) args[0]).append( RESPONSE.substring(bufferSize * 2, bufferSize * 3)); return RESPONSE.length(); }) .doAnswer(invocation -> { Object[] args = invocation.getArguments(); ((CharBuffer) args[0]).append( RESPONSE.substring(bufferSize * 3, RESPONSE.length())); return RESPONSE.length(); }) .when(reader).read(any(CharBuffer.class)); runTest(); }
.doAnswer(invocation -> { ByteBuffer buffer = invocation.getArgument(0); CompletionHandler<Integer, ByteBuffer> completionHandler =
@Override public StaticCapableStubber doAnswer(Answer answer) { instanceStubber = instanceStubber.doAnswer(answer); return this; }
final CountDownLatch completionLatch = new CountDownLatch( 1 ); Mockito.doNothing().doAnswer( invocation ->
@Test public void getProperties_return_properties_from_previous_thread_cache_if_DB_error_on_not_first_call() { String key = randomAlphanumeric(3); String value1 = randomAlphanumeric(4); String value2 = randomAlphanumeric(5); SettingLoader settingLoaderMock = mock(SettingLoader.class); PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB"); doAnswer(invocationOnMock -> ImmutableMap.of(key, value1)) .doThrow(toBeThrown) .doAnswer(invocationOnMock -> ImmutableMap.of(key, value2)) .when(settingLoaderMock) .loadAll(); underTest = new ThreadLocalSettings(new PropertyDefinitions(), new Properties(), settingLoaderMock); underTest.load(); assertThat(underTest.getProperties()) .containsOnly(entry(key, value1)); underTest.unload(); underTest.load(); assertThat(underTest.getProperties()) .containsOnly(entry(key, value1)); underTest.unload(); underTest.load(); assertThat(underTest.getProperties()) .containsOnly(entry(key, value2)); underTest.unload(); }
@Override public Stubber doAnswer(final Answer answer) {return stubber.doAnswer(answer);}
public BDDStubber willAnswer(Answer answer) { return new BDDStubberImpl(mockitoStubber.doAnswer(answer)); }
@Test public void testCloseShouldRetryOnceOnInterruptedException() { ZkClient zkClient = Mockito.mock(ZkClient.class); ZkUtils zkUtils = new ZkUtils(KEY_BUILDER, zkClient, CONNECTION_TIMEOUT_MS, SESSION_TIMEOUT_MS, new NoOpMetricsRegistry()); Mockito.doThrow(new ZkInterruptedException(new InterruptedException())) .doAnswer(invocation -> null) .when(zkClient).close(); zkUtils.close(); Mockito.verify(zkClient, Mockito.times(2)).close(); }
@Test public void retryOnceThenFail() { final HttpException expectedException = new HttpException(403); final ServiceCallback callback = mock(ServiceCallback.class); HttpClient httpClient = mock(HttpClient.class); doAnswer(new Answer<ServiceCall>() { @Override public ServiceCall answer(InvocationOnMock invocationOnMock) { ((ServiceCallback) invocationOnMock.getArguments()[4]).onCallFailed(new UnknownHostException()); return mock(ServiceCall.class); } }).doAnswer(new Answer<ServiceCall>() { @Override public ServiceCall answer(InvocationOnMock invocationOnMock) { ((ServiceCallback) invocationOnMock.getArguments()[4]).onCallFailed(expectedException); return mock(ServiceCall.class); } }).when(httpClient).callAsync(anyString(), anyString(), anyMapOf(String.class, String.class), any(HttpClient.CallTemplate.class), any(ServiceCallback.class)); Handler handler = mock(Handler.class); HttpClient retryer = new HttpClientRetryer(httpClient, handler); simulateRetryAfterDelay(handler); retryer.callAsync(null, null, null, null, callback); verifyDelay(handler, 0); verifyNoMoreInteractions(handler); verify(callback).onCallFailed(any(Exception.class)); verify(callback).onCallFailed(expectedException); verifyNoMoreInteractions(callback); }
@Test public void successAfterOneRetry() { final ServiceCallback callback = mock(ServiceCallback.class); HttpClient httpClient = mock(HttpClient.class); doAnswer(new Answer<ServiceCall>() { @Override public ServiceCall answer(InvocationOnMock invocationOnMock) { ((ServiceCallback) invocationOnMock.getArguments()[4]).onCallFailed(new SocketException()); return mock(ServiceCall.class); } }).doAnswer(new Answer<ServiceCall>() { @Override public ServiceCall answer(InvocationOnMock invocationOnMock) { ((ServiceCallback) invocationOnMock.getArguments()[4]).onCallSucceeded("mockSuccessPayload"); return mock(ServiceCall.class); } }).when(httpClient).callAsync(anyString(), anyString(), anyMapOf(String.class, String.class), any(HttpClient.CallTemplate.class), any(ServiceCallback.class)); Handler handler = mock(Handler.class); HttpClient retryer = new HttpClientRetryer(httpClient, handler); simulateRetryAfterDelay(handler); retryer.callAsync(null, null, null, null, callback); verifyDelay(handler, 0); verifyNoMoreInteractions(handler); verify(callback).onCallSucceeded("mockSuccessPayload"); verifyNoMoreInteractions(callback); }
.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock unused) {
.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock unused) {