org.mockito.stubbing.Stubber Java Examples

The following examples show how to use org.mockito.stubbing.Stubber. 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: MockitoUtil.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Throw an exception from the mock/spy only in the case that the
 * call stack at the time the method has a line which matches the given
 * pattern.
 *
 * @param t the Throwable to throw
 * @param pattern the pattern against which to match the call stack trace
 * @return the stub in progress
 */
public static Stubber doThrowWhenCallStackMatches(
    final Throwable t, final String pattern) {
  return Mockito.doAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      t.setStackTrace(Thread.currentThread().getStackTrace());
      for (StackTraceElement elem : t.getStackTrace()) {
        if (elem.toString().matches(pattern)) {
          throw t;
        }
      }
      return invocation.callRealMethod();
    }
  });
}
 
Example #2
Source File: ClientTest.java    From joal with Apache License 2.0 6 votes vote down vote up
private TorrentFileProvider createMockedTorrentFileProviderWithTorrent(final Iterable<MockedTorrent> mockedTorrents) {
    final TorrentFileProvider torrentFileProvider = mock(TorrentFileProvider.class);
    Stubber stubber = null;
    for (final MockedTorrent torrent : mockedTorrents) {
        if (stubber == null) {
            stubber = doReturn(torrent);
        } else {
            stubber = stubber.doReturn(torrent);
        }
    }
    try {
        if (stubber == null) {
            Mockito.doThrow(new NoMoreTorrentsFileAvailableException("no more")).when(torrentFileProvider).getTorrentNotIn(anyList());
        } else {
            stubber
                    .doThrow(new NoMoreTorrentsFileAvailableException("no more"))
                    .when(torrentFileProvider).getTorrentNotIn(anyList());
        }
    } catch (final NoMoreTorrentsFileAvailableException ignore) {
    }

    return torrentFileProvider;
}
 
Example #3
Source File: MockitoUtil.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Throw an exception from the mock/spy only in the case that the
 * call stack at the time the method has a line which matches the given
 * pattern.
 *
 * @param t the Throwable to throw
 * @param pattern the pattern against which to match the call stack trace
 * @return the stub in progress
 */
public static Stubber doThrowWhenCallStackMatches(
    final Throwable t, final String pattern) {
  return Mockito.doAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      t.setStackTrace(Thread.currentThread().getStackTrace());
      for (StackTraceElement elem : t.getStackTrace()) {
        if (elem.toString().matches(pattern)) {
          throw t;
        }
      }
      return invocation.callRealMethod();
    }
  });
}
 
Example #4
Source File: LocationEngineTest.java    From mapbox-events-android with MIT License 5 votes vote down vote up
private static Stubber setupDoAnswer(final LocationEngineResult expectedResult) {
  return doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) {
      LocationEngineCallback<LocationEngineResult> callback = invocation.getArgument(0);
      callback.onSuccess(expectedResult);
      return null;
    }
  });
}
 
Example #5
Source File: Expect.java    From lambda-behave with MIT License 5 votes vote down vote up
private  Stubber doAnswer(final Consumer<Object[]> method, final int argumentCount) {
    return Mockito.doAnswer(invocation -> {
        Object[] arguments = invocation.getArguments();
        if (arguments.length >= argumentCount) {
            method.accept(arguments);
        } else {
            failure("Invocation requires at least " + argumentCount + " argument");
        }
        return null;
    });
}
 
Example #6
Source File: Expect.java    From lambda-behave with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> Stubber toAnswer(final Runnable method) {
    return Mockito.doAnswer(invocation -> {
        Object[] arguments = invocation.getArguments();
        method.run();
        return null;
    });
}
 
Example #7
Source File: DataStoreJerseyTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
private Stubber captureUpdatesAndTags(final List<Update> updates, final Set<String> tags) {
    return doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation)
                throws Throwable {
            //noinspection unchecked
            Iterables.addAll(updates, (Iterable<Update>) invocation.getArguments()[0]);
            //noinspection unchecked
            tags.addAll((Collection<? extends String>) invocation.getArguments()[1]);
            return null;
        }
    });
}
 
Example #8
Source File: DataStoreJerseyTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
private Stubber doUpdateInto(final List<Update> updates) {
    return doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation)
                throws Throwable {
            //noinspection unchecked
            Iterables.addAll(updates, (Iterable<Update>) invocation.getArguments()[0]);
            return null;
        }
    });
}
 
Example #9
Source File: ServiceAuthenticationServiceImplTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private AuthenticationCommand testRequiredAuthentication(boolean requiredJwtValidation, String jwtToken) throws Exception {
    Authentication authentication = new Authentication(AuthenticationScheme.HTTP_BASIC_PASSTICKET, "applid");
    ServiceAuthenticationServiceImpl.UniversalAuthenticationCommand universalAuthenticationCommand =
        serviceAuthenticationServiceImpl.new UniversalAuthenticationCommand();

    AuthenticationCommand ac = mock(AuthenticationCommand.class);
    QueryResponse queryResponse = mock(QueryResponse.class);
    AbstractAuthenticationScheme schema = mock(AbstractAuthenticationScheme.class);
    HttpServletRequest request = mock(HttpServletRequest.class);
    RequestContext.getCurrentContext().setRequest(request);

    Stubber stubber;
    if (StringUtils.equals(jwtToken, "validJwt")) {
        stubber = doReturn(Optional.of(jwtToken));
    } else {
        stubber = doThrow(new TokenNotValidException("Token is not valid."));
    }
    stubber.when(getUnProxy(authenticationService)).getJwtTokenFromRequest(request);
    doReturn(ac).when(schema).createCommand(eq(authentication), argThat(x -> Objects.equals(x.get(), queryResponse)));
    doReturn(schema).when(getUnProxy(authenticationSchemeFactory)).getSchema(authentication.getScheme());
    doReturn(queryResponse).when(getUnProxy(authenticationService)).parseJwtToken("validJwt");
    doReturn(requiredJwtValidation).when(ac).isRequiredValidJwt();

    universalAuthenticationCommand.apply(createInstanceInfo("id", authentication));

    return ac;
}
 
Example #10
Source File: StubberImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Stubber doThrow(Throwable toBeThrown) {
    answers.add(new ThrowsException(toBeThrown));
    return this;
}
 
Example #11
Source File: StubberImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Stubber doReturn(Object toBeReturned) {
    answers.add(new Returns(toBeReturned));
    return this;
}
 
Example #12
Source File: StubberImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Stubber doNothing() {
    answers.add(new DoesNothing());
    return this;
}
 
Example #13
Source File: StubberImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Stubber doAnswer(Answer answer) {
    answers.add(answer);
    return this;
}
 
Example #14
Source File: BDDMockito.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public BDDStubberImpl(Stubber mockitoStubber) {
    this.mockitoStubber = mockitoStubber;
}
 
Example #15
Source File: MockitoCore.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Stubber doAnswer(Answer answer) {
    mockingProgress.stubbingStarted();
    mockingProgress.resetOngoingStubbing();
    return new StubberImpl().doAnswer(answer);
}
 
Example #16
Source File: StubberImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Stubber doReturn(Object toBeReturned) {
    answers.add(new Returns(toBeReturned));
    return this;
}
 
Example #17
Source File: StubberImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Stubber doThrow(Throwable toBeThrown) {
    answers.add(new ThrowsException(toBeThrown));
    return this;
}
 
Example #18
Source File: StubberImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Stubber doThrow(Class<? extends Throwable> toBeThrown) {
    answers.add(new ThrowsExceptionClass(toBeThrown));
    return this;
}
 
Example #19
Source File: StubberImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Stubber doNothing() {
    answers.add(new DoesNothing());
    return this;
}
 
Example #20
Source File: StubberImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Stubber doAnswer(Answer answer) {
    answers.add(answer);
    return this;
}
 
Example #21
Source File: StubberImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Stubber doCallRealMethod() {
    answers.add(new CallsRealMethods());
    return this;
}
 
Example #22
Source File: BDDMockito.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public BDDStubberImpl(Stubber mockitoStubber) {
    this.mockitoStubber = mockitoStubber;
}
 
Example #23
Source File: StatsDReporterTest.java    From kafka-statsd-metrics2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
static <T extends Metric> T configureMatcher(T mock, Stubber stub) throws Exception {
  stub.when(mock).processWith(any(MetricProcessor.class), any(MetricName.class), any());
  return mock;
}
 
Example #24
Source File: StaticCapableStubber.java    From dexmaker with Apache License 2.0 4 votes vote down vote up
StaticCapableStubber(Stubber instanceStubber) {
    this.instanceStubber = instanceStubber;
}
 
Example #25
Source File: TestQuorumJournalManager.java    From hadoop with Apache License 2.0 4 votes vote down vote up
private Stubber injectIOE() {
  return futureThrows(new IOException("Injected"));
}
 
Example #26
Source File: Expect.java    From lambda-behave with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> Stubber toAnswer(final Consumer<T> method) {
    return doAnswer(arguments -> method.accept((T) arguments[0]), 1);
}
 
Example #27
Source File: Expect.java    From lambda-behave with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
public <F, S> Stubber toAnswer(final BiConsumer<F, S> method) {
    return doAnswer(arguments ->
        method.accept((F) arguments[0], (S) arguments[1]), 2);
}
 
Example #28
Source File: Expect.java    From lambda-behave with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
public <F, S, T> Stubber toAnswer(final TriConsumer<F, S, T> method) {
    return doAnswer(arguments ->
            method.accept((F) arguments[0], (S) arguments[1], (T) arguments[2]), 3);
}
 
Example #29
Source File: WithMockito.java    From mockito-java8 with Apache License 2.0 4 votes vote down vote up
/**
 * Delegates call to {@link Mockito#doAnswer(Answer)}.
 */
default Stubber doAnswer(Answer answer) {
    return Mockito.doAnswer(answer);
}
 
Example #30
Source File: TestQuorumJournalManagerUnit.java    From big-c with Apache License 2.0 4 votes vote down vote up
static Stubber futureThrows(Throwable t) {
  ListenableFuture<?> ret = Futures.immediateFailedFuture(t);
  return Mockito.doReturn(ret);
}