下面列出了怎么用org.mockito.internal.stubbing.answers.ThrowsException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testOnNextThrowingException() {
Subscriber<Integer> subscriber = mock(Subscriber.class);
IllegalArgumentException boom = new IllegalArgumentException("boom");
doAnswer(new ThrowsException(boom)).when(subscriber).onNext(2);
Subscription subscription = mock(Subscription.class);
SafeSubscriber<Integer> safe = new SafeSubscriber<>(subscriber);
safe.onSubscribe(subscription);
verify(subscriber, times(1)).onSubscribe(safe);
safe.onNext(1);
verify(subscriber, times(1)).onNext(1);
// inject the failing item
safe.onNext(2);
verify(subscriber, times(1)).onNext(2);
verify(subscriber, times(1)).onError(boom);
assertThat(safe.isDone()).isTrue();
}
@Test
public void testOnNextThrowingExceptionFollowedByCancellationFailure() {
Subscriber<Integer> subscriber = mock(Subscriber.class);
IllegalArgumentException boom = new IllegalArgumentException("boom");
doAnswer(new ThrowsException(boom)).when(subscriber).onNext(2);
Subscription subscription = mock(Subscription.class);
doAnswer(new ThrowsException(new NullPointerException())).when(subscription).cancel();
SafeSubscriber<Integer> safe = new SafeSubscriber<>(subscriber);
safe.onSubscribe(subscription);
verify(subscriber, times(1)).onSubscribe(safe);
safe.onNext(1);
verify(subscriber, times(1)).onNext(1);
// inject the failing item
safe.onNext(2);
verify(subscriber, times(1)).onNext(2);
verify(subscriber, times(1)).onError(any(CompositeException.class)); // boom + NPE
assertThat(safe.isDone()).isTrue();
}
@Test
public void testThatDownstreamFailuresAreHandledInOnError() {
Subscriber<String> subscriber = mock(Subscriber.class);
doAnswer(new ThrowsException(new IllegalStateException("boom"))).when(subscriber).onError(any());
Subscription subscription = mock(Subscription.class);
SafeSubscriber<String> safe = new SafeSubscriber<>(subscriber);
safe.onSubscribe(subscription);
verify(subscriber, times(1)).onSubscribe(safe);
Exception boom = new Exception("boom");
safe.onError(boom);
// called
verify(subscriber, times(1)).onError(boom);
assertThat(safe.isDone()).isTrue();
}
@Test
public void testFailureInDownstreamOnComplete() {
Subscriber<Integer> subscriber = mock(Subscriber.class);
IllegalArgumentException boom = new IllegalArgumentException("boom");
doAnswer(new ThrowsException(boom)).when(subscriber).onComplete();
Subscription subscription = mock(Subscription.class);
SafeSubscriber<Integer> safe = new SafeSubscriber<>(subscriber);
safe.onSubscribe(subscription);
verify(subscriber, times(1)).onSubscribe(safe);
safe.onNext(1);
verify(subscriber, times(1)).onNext(1);
safe.onComplete();
verify(subscriber, times(1)).onComplete();
verify(subscriber, times(0)).onError(any()); // cannot report.
assertThat(safe.isDone()).isTrue();
}
@Test
public void shouldGetResultsForMethods() throws Throwable {
invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod));
invocationContainerImpl.addAnswer(new Returns("simpleMethod"));
Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation();
invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod));
invocationContainerImpl.addAnswer(new ThrowsException(new MyException()));
assertEquals("simpleMethod", invocationContainerImpl.answerTo(simpleMethod));
try {
invocationContainerImpl.answerTo(differentMethod);
fail();
} catch (MyException e) {}
}
@Test
public void should_get_results_for_methods() throws Throwable {
invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod));
invocationContainerImpl.addAnswer(new Returns("simpleMethod"));
Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation();
invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod));
invocationContainerImpl.addAnswer(new ThrowsException(new MyException()));
assertEquals("simpleMethod", invocationContainerImpl.answerTo(simpleMethod));
try {
invocationContainerImpl.answerTo(differentMethod);
fail();
} catch (MyException e) {}
}
@Test
public void should_get_results_for_methods_stub_only() throws Throwable {
invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod));
invocationContainerImplStubOnly.addAnswer(new Returns("simpleMethod"));
Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation();
invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod));
invocationContainerImplStubOnly.addAnswer(new ThrowsException(new MyException()));
assertEquals("simpleMethod", invocationContainerImplStubOnly.answerTo(simpleMethod));
try {
invocationContainerImplStubOnly.answerTo(differentMethod);
fail();
} catch (MyException e) {}
}
@Test
public void testThatDownstreamFailureInOnSubscribeCancelsTheSubscription() {
Subscriber<Integer> subscriber = mock(Subscriber.class);
doAnswer(new ThrowsException(new IllegalStateException("boom"))).when(subscriber).onSubscribe(any());
Subscription subscription = mock(Subscription.class);
SafeSubscriber<Integer> safe = new SafeSubscriber<>(subscriber);
safe.onSubscribe(subscription);
verify(subscription, times(1)).cancel();
assertThat(safe.isDone()).isTrue();
}
@Test
public void testDownstreamFailureInOnSubscribeFollowedByACancellationFailure() {
Subscriber<Integer> subscriber = mock(Subscriber.class);
doAnswer(new ThrowsException(new IllegalStateException("boom"))).when(subscriber).onSubscribe(any());
Subscription subscription = mock(Subscription.class);
doAnswer(new ThrowsException(new NullPointerException())).when(subscription).cancel();
SafeSubscriber<Integer> safe = new SafeSubscriber<>(subscriber);
safe.onSubscribe(subscription);
verify(subscription, times(1)).cancel();
assertThat(safe.isDone()).isTrue();
}
@Test
public void testThatOnErrorWithoutSubscriptionFollowedBySubscriptionFailureIsAProtocolViolationButCannotBeReportedDownstream() {
Subscriber<String> subscriber = mock(Subscriber.class);
doAnswer(new ThrowsException(new IllegalStateException("boom"))).when(subscriber).onSubscribe(any());
SafeSubscriber<String> safe = new SafeSubscriber<>(subscriber);
safe.onError(new IllegalArgumentException("boom"));
verify(subscriber, times(0)).onError(any(Exception.class));
verify(subscriber, times(1)).onSubscribe(any(Subscriptions.EmptySubscription.class)); // failing
assertThat(safe.isDone()).isTrue();
}
@Test
public void testWhenUpstreamCancellationFails() {
Subscriber<Integer> subscriber = mock(Subscriber.class);
Subscription subscription = mock(Subscription.class);
doAnswer(new ThrowsException(new IllegalStateException("boom"))).when(subscription).cancel();
SafeSubscriber<Integer> safe = new SafeSubscriber<>(subscriber);
safe.onSubscribe(subscription);
verify(subscriber, times(1)).onSubscribe(safe);
safe.cancel();
}
@Test
public void testWhenUpstreamRequestFails() {
Subscriber<Integer> subscriber = mock(Subscriber.class);
Subscription subscription = mock(Subscription.class);
doAnswer(new ThrowsException(new IllegalStateException("boom"))).when(subscription).request(anyLong());
SafeSubscriber<Integer> safe = new SafeSubscriber<>(subscriber);
safe.onSubscribe(subscription);
verify(subscriber, times(1)).onSubscribe(safe);
safe.request(25L);
}
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
// Getting a proxy to a dead server will throw IOException on call,
// not on creation of the proxy.
HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
Mockito.withSettings()
.defaultAnswer(new ThrowsException(
new IOException("Could not connect to host")))
.extraInterfaces(Closeable.class));
Mockito.doNothing().when((Closeable)errorThrowingProxy).close();
Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
Mockito.<Configuration>any(),
Mockito.anyInt());
DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());
try {
doFailover(svc1, svc2, false, false);
} catch (FailoverFailedException ffe) {
fail("Non-existant active prevented failover");
}
// Verify that the proxy created to try to make it go to standby
// gracefully used the right rpc timeout
Mockito.verify(svc1).getProxy(
Mockito.<Configuration>any(),
Mockito.eq(
CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));
// Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
assertEquals(HAServiceState.ACTIVE, svc2.state);
}
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
// Getting a proxy to a dead server will throw IOException on call,
// not on creation of the proxy.
HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
Mockito.withSettings()
.defaultAnswer(new ThrowsException(
new IOException("Could not connect to host")))
.extraInterfaces(Closeable.class));
Mockito.doNothing().when((Closeable)errorThrowingProxy).close();
Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
Mockito.<Configuration>any(),
Mockito.anyInt());
DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());
try {
doFailover(svc1, svc2, false, false);
} catch (FailoverFailedException ffe) {
fail("Non-existant active prevented failover");
}
// Verify that the proxy created to try to make it go to standby
// gracefully used the right rpc timeout
Mockito.verify(svc1).getProxy(
Mockito.<Configuration>any(),
Mockito.eq(
CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));
// Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
assertEquals(HAServiceState.ACTIVE, svc2.state);
}
public void testExecuteOperationsSetsErrorOnInvalidRequestException() throws Exception {
String operationId = "op1";
OperationRequest operation = new OperationRequest("wavelet.create", operationId);
OperationService service =
mock(OperationService.class, new ThrowsException(new InvalidRequestException("")));
when(operationRegistry.getServiceFor(any(OperationType.class))).thenReturn(service);
OperationUtil.executeOperation(operation, operationRegistry, context, ALEX);
assertTrue("Expected one response", context.getResponses().size() == 1);
assertTrue("Expected an error response", context.getResponse(operationId).isError());
}
@Test
public void shouldAllowThrowsExceptionToBeSerializable() throws Exception {
// given
Bar mock = mock(Bar.class, new ThrowsException(new RuntimeException()));
// when-serialize then-deserialize
serializeAndBack(mock);
}
@Test
public void shouldAllowMethodDelegation() throws Exception {
// given
Bar barMock = mock(Bar.class, withSettings().serializable());
Foo fooMock = mock(Foo.class);
when(barMock.doSomething()).thenAnswer(new ThrowsException(new RuntimeException()));
//when-serialize then-deserialize
serializeAndBack(barMock);
}
@Test
public void shouldFinishStubbingWhenWrongThrowableIsSet() throws Exception {
state.stubbingStarted();
try {
invocationContainerImpl.addAnswer(new ThrowsException(new Exception()));
fail();
} catch (MockitoException e) {
state.validateState();
}
}
@Test
public void shouldAddThrowableForVoidMethod() throws Throwable {
invocationContainerImpl.addAnswerForVoidMethod(new ThrowsException(new MyException()));
invocationContainerImpl.setMethodForStubbing(new InvocationMatcher(simpleMethod));
try {
invocationContainerImpl.answerTo(simpleMethod);
fail();
} catch (MyException e) {}
}
@Test
public void shouldValidateThrowableForVoidMethod() throws Throwable {
invocationContainerImpl.addAnswerForVoidMethod(new ThrowsException(new Exception()));
try {
invocationContainerImpl.setMethodForStubbing(new InvocationMatcher(simpleMethod));
fail();
} catch (MockitoException e) {}
}
@Test
public void shouldValidateThrowable() throws Throwable {
try {
invocationContainerImpl.addAnswer(new ThrowsException(null));
fail();
} catch (MockitoException e) {}
}
@Test
public void should_allow_throws_exception_to_be_serializable() throws Exception {
// given
when(barMock.doSomething()).thenAnswer(new ThrowsException(new RuntimeException()));
//when-serialize then-deserialize
serializeAndBack(barMock);
}
@Test
public void should_allow_throws_exception_to_be_serializable() throws Exception {
// given
Bar mock = mock(Bar.class, new ThrowsException(new RuntimeException()));
// when-serialize then-deserialize
serializeAndBack(mock);
}
@Test
public void should_allow_method_delegation() throws Exception {
// given
Bar barMock = mock(Bar.class, withSettings().serializable());
Foo fooMock = mock(Foo.class);
when(barMock.doSomething()).thenAnswer(new ThrowsException(new RuntimeException()));
//when-serialize then-deserialize
serializeAndBack(barMock);
}
@Test
public void should_finish_stubbing_when_wrong_throwable_is_set() throws Exception {
state.stubbingStarted();
try {
invocationContainerImpl.addAnswer(new ThrowsException(new Exception()));
fail();
} catch (MockitoException e) {
state.validateState();
}
}
@Test
public void should_add_throwable_for_void_method() throws Throwable {
invocationContainerImpl.addAnswerForVoidMethod(new ThrowsException(new MyException()));
invocationContainerImpl.setMethodForStubbing(new InvocationMatcher(simpleMethod));
try {
invocationContainerImpl.answerTo(simpleMethod);
fail();
} catch (MyException e) {}
}
@Test
public void should_validate_throwable_for_void_method() throws Throwable {
invocationContainerImpl.addAnswerForVoidMethod(new ThrowsException(new Exception()));
try {
invocationContainerImpl.setMethodForStubbing(new InvocationMatcher(simpleMethod));
fail();
} catch (MockitoException e) {}
}
@Test
public void should_validate_throwable() throws Throwable {
try {
invocationContainerImpl.addAnswer(new ThrowsException(null));
fail();
} catch (MockitoException e) {}
}
public void testExecuteOperationsSetsErrorOnInvalidRequestException() throws Exception {
String operationId = "op1";
OperationRequest operation = new OperationRequest("wavelet.create", operationId);
OperationService service =
mock(OperationService.class, new ThrowsException(new InvalidRequestException("")));
when(operationRegistry.getServiceFor(any(OperationType.class))).thenReturn(service);
OperationUtil.executeOperation(operation, operationRegistry, context, ALEX);
assertTrue("Expected one response", context.getResponses().size() == 1);
assertTrue("Expected an error response", context.getResponse(operationId).isError());
}
/**
* Verify that client will correctly give up after the specified number
* of times trying to add a block
*/
@SuppressWarnings({ "serial", "unchecked" })
@Test
public void testNotYetReplicatedErrors() throws IOException
{
final String exceptionMsg = "Nope, not replicated yet...";
final int maxRetries = 1; // Allow one retry (total of two calls)
conf.setInt(DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY, maxRetries);
NamenodeProtocols mockNN = mock(NamenodeProtocols.class);
Answer<Object> answer = new ThrowsException(new IOException()) {
int retryCount = 0;
@Override
public Object answer(InvocationOnMock invocation)
throws Throwable {
retryCount++;
System.out.println("addBlock has been called " + retryCount + " times");
if(retryCount > maxRetries + 1) // First call was not a retry
throw new IOException("Retried too many times: " + retryCount);
else
throw new RemoteException(NotReplicatedYetException.class.getName(),
exceptionMsg);
}
};
when(mockNN.addBlock(anyString(),
anyString(),
any(ExtendedBlock.class),
any(DatanodeInfo[].class),
anyLong(), any(String[].class))).thenAnswer(answer);
Mockito.doReturn(
new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
(short) 777), "owner", "group", new byte[0], new byte[0],
1010, 0, null, (byte) 0)).when(mockNN).getFileInfo(anyString());
Mockito.doReturn(
new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
(short) 777), "owner", "group", new byte[0], new byte[0],
1010, 0, null, (byte) 0))
.when(mockNN)
.create(anyString(), (FsPermission) anyObject(), anyString(),
(EnumSetWritable<CreateFlag>) anyObject(), anyBoolean(),
anyShort(), anyLong(), (CryptoProtocolVersion[]) anyObject());
final DFSClient client = new DFSClient(null, mockNN, conf, null);
OutputStream os = client.create("testfile", true);
os.write(20); // write one random byte
try {
os.close();
} catch (Exception e) {
assertTrue("Retries are not being stopped correctly: " + e.getMessage(),
e.getMessage().equals(exceptionMsg));
}
}