org.mockito.internal.stubbing.answers.ThrowsException Java Examples

The following examples show how to use org.mockito.internal.stubbing.answers.ThrowsException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SafeSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #2
Source File: SafeSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #3
Source File: MockitoStubberTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@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) {}
}
 
Example #4
Source File: SafeSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #5
Source File: SafeSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #6
Source File: InvocationContainerImplStubbingTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@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) {}
}
 
Example #7
Source File: InvocationContainerImplStubbingTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@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) {}
}
 
Example #8
Source File: MockitoStubberTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldFinishStubbingWhenWrongThrowableIsSet() throws Exception {
    state.stubbingStarted();
    try {
        invocationContainerImpl.addAnswer(new ThrowsException(new Exception()));
        fail();
    } catch (MockitoException e) {
        state.validateState();
    }
}
 
Example #9
Source File: MocksSerializationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldAllowThrowsExceptionToBeSerializable() throws Exception {
    // given
    Bar mock = mock(Bar.class, new ThrowsException(new RuntimeException()));
    // when-serialize then-deserialize
    serializeAndBack(mock);
}
 
Example #10
Source File: MockitoStubberTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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) {}
}
 
Example #11
Source File: MockitoStubberTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldValidateThrowableForVoidMethod() throws Throwable {
    invocationContainerImpl.addAnswerForVoidMethod(new ThrowsException(new Exception()));
    
    try {
        invocationContainerImpl.setMethodForStubbing(new InvocationMatcher(simpleMethod));
        fail();
    } catch (MockitoException e) {}
}
 
Example #12
Source File: MockitoStubberTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldValidateThrowable() throws Throwable {
    try {
        invocationContainerImpl.addAnswer(new ThrowsException(null));
        fail();
    } catch (MockitoException e) {}
}
 
Example #13
Source File: MocksSerializationForAnnotationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #14
Source File: MocksSerializationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #15
Source File: MocksSerializationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #16
Source File: InvocationContainerImplStubbingTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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();
    }
}
 
Example #17
Source File: InvocationContainerImplStubbingTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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) {}
}
 
Example #18
Source File: InvocationContainerImplStubbingTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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) {}
}
 
Example #19
Source File: InvocationContainerImplStubbingTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_validate_throwable() throws Throwable {
    try {
        invocationContainerImpl.addAnswer(new ThrowsException(null));
        fail();
    } catch (MockitoException e) {}
}
 
Example #20
Source File: OperationUtilTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #21
Source File: SafeSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #22
Source File: SafeSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #23
Source File: SafeSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #24
Source File: SafeSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #25
Source File: SafeSubscriberTest.java    From smallrye-mutiny with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #26
Source File: TestFailoverController.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #27
Source File: TestFailoverController.java    From big-c with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #28
Source File: OperationUtilTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #29
Source File: MocksSerializationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #30
Source File: BaseStubbing.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public DeprecatedOngoingStubbing<T> toThrow(Throwable throwable) {
    return toAnswer(new ThrowsException(throwable));
}