下面列出了org.mockito.internal.stubbing.answers.ThrowsException#org.mockito.stubbing.Stubber 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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();
}
});
}
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;
}
/**
* 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();
}
});
}
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;
}
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;
}
});
}
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;
}
});
}
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;
}
});
}
@SuppressWarnings("unchecked")
public <T> Stubber toAnswer(final Runnable method) {
return Mockito.doAnswer(invocation -> {
Object[] arguments = invocation.getArguments();
method.run();
return null;
});
}
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;
});
}
private Stubber injectIOE() {
return futureThrows(new IOException("Injected"));
}
static <V> Stubber futureReturns(V value) {
ListenableFuture<V> ret = Futures.immediateFuture(value);
return Mockito.doReturn(ret);
}
static Stubber futureThrows(Throwable t) {
ListenableFuture<?> ret = Futures.immediateFailedFuture(t);
return Mockito.doReturn(ret);
}
private Stubber injectIOE() {
return futureThrows(new IOException("Injected"));
}
static <V> Stubber futureReturns(V value) {
ListenableFuture<V> ret = Futures.immediateFuture(value);
return Mockito.doReturn(ret);
}
static Stubber futureThrows(Throwable t) {
ListenableFuture<?> ret = Futures.immediateFailedFuture(t);
return Mockito.doReturn(ret);
}
@Test
public void shouldRenderKSQLSelectAsTable() throws InterpreterException,
IOException, InterruptedException {
// given
Properties p = new Properties();
p.putAll(PROPS);
KSQLRestService service = Mockito.mock(KSQLRestService.class);
Stubber stubber = Mockito.doAnswer((invocation) -> {
Consumer< KSQLResponse> callback = (Consumer< KSQLResponse>)
invocation.getArguments()[2];
IntStream.range(1, 5)
.forEach(i -> {
Map<String, Object> map = new HashMap<>();
if (i == 4) {
map.put("row", null);
map.put("terminal", true);
} else {
map.put("row", Collections.singletonMap("columns", Arrays.asList("value " + i)));
map.put("terminal", false);
}
callback.accept(new KSQLResponse(Arrays.asList("fieldName"), map));
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
return null;
});
stubber.when(service).executeQuery(Mockito.any(String.class),
Mockito.anyString(),
Mockito.any(Consumer.class));
Interpreter interpreter = new KSQLInterpreter(p, service);
// when
String query = "select * from orders";
interpreter.interpret(query, context);
// then
String expected = "%table fieldName\n" +
"value 1\n" +
"value 2\n" +
"value 3\n";
assertEquals(1, context.out.toInterpreterResultMessage().size());
assertEquals(expected, context.out.toInterpreterResultMessage().get(0).toString());
assertEquals(InterpreterResult.Type.TABLE, context.out
.toInterpreterResultMessage().get(0).getType());
interpreter.close();
}
@Test
public void shouldRenderKSQLNonSelectAsTable() throws InterpreterException,
IOException, InterruptedException {
// given
Properties p = new Properties();
p.putAll(PROPS);
KSQLRestService service = Mockito.mock(KSQLRestService.class);
Map<String, Object> row1 = new HashMap<>();
row1.put("name", "orders");
row1.put("registered", "false");
row1.put("replicaInfo", "[1]");
row1.put("consumerCount", "0");
row1.put("consumerGroupCount", "0");
Map<String, Object> row2 = new HashMap<>();
row2.put("name", "orders");
row2.put("registered", "false");
row2.put("replicaInfo", "[1]");
row2.put("consumerCount", "0");
row2.put("consumerGroupCount", "0");
Stubber stubber = Mockito.doAnswer((invocation) -> {
Consumer< KSQLResponse> callback = (Consumer< KSQLResponse>)
invocation.getArguments()[2];
callback.accept(new KSQLResponse(row1));
callback.accept(new KSQLResponse(row2));
return null;
});
stubber.when(service).executeQuery(
Mockito.any(String.class),
Mockito.anyString(),
Mockito.any(Consumer.class));
Interpreter interpreter = new KSQLInterpreter(p, service);
// when
String query = "show topics";
interpreter.interpret(query, context);
// then
List<Map<String, Object>> expected = Arrays.asList(row1, row2);
String[] lines = context.out.toInterpreterResultMessage()
.get(0).toString()
.replace("%table ", "")
.trim()
.split("\n");
List<String[]> rows = Stream.of(lines)
.map(line -> line.split("\t"))
.collect(Collectors.toList());
List<Map<String, String>> actual = rows.stream()
.skip(1)
.map(row -> IntStream.range(0, row.length)
.mapToObj(index -> new AbstractMap.SimpleEntry<>(rows.get(0)[index], row[index]))
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())))
.collect(Collectors.toList());
assertEquals(1, context.out.toInterpreterResultMessage().size());
assertEquals(expected, actual);
assertEquals(InterpreterResult.Type.TABLE, context.out
.toInterpreterResultMessage().get(0).getType());
}
/**
* Delegates call to {@link Mockito#doThrow(Throwable...)}.
*/
default Stubber doThrow(Throwable... toBeThrown) {
return Mockito.doThrow(toBeThrown);
}
/**
* Delegates call to {@link Mockito#doThrow(Class)}.
*/
default Stubber doThrow(Class<? extends Throwable> toBeThrown) {
return Mockito.doThrow(toBeThrown);
}
/**
* Delegates call to {@link Mockito#doCallRealMethod()}.
*/
default Stubber doCallRealMethod() {
return Mockito.doCallRealMethod();
}
/**
* Delegates call to {@link Mockito#doAnswer(Answer)}.
*/
default Stubber doAnswer(Answer answer) {
return Mockito.doAnswer(answer);
}
/**
* Delegates call to {@link Mockito#doNothing()}.
*/
default Stubber doNothing() {
return Mockito.doNothing();
}
/**
* Delegates call to {@link Mockito#doReturn(Object)}.
*/
default Stubber doReturn(Object toBeReturned) {
return Mockito.doReturn(toBeReturned);
}
/**
* Delegates call to {@link Mockito#doReturn(Object, Object...)}.
*/
default Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {
return Mockito.doReturn(toBeReturned, toBeReturnedNext);
}
public Stubber doAnswer(Answer answer) {
mockingProgress.stubbingStarted();
mockingProgress.resetOngoingStubbing();
return new StubberImpl().doAnswer(answer);
}
public Stubber doReturn(Object toBeReturned) {
answers.add(new Returns(toBeReturned));
return this;
}
public Stubber doThrow(Throwable toBeThrown) {
answers.add(new ThrowsException(toBeThrown));
return this;
}
public Stubber doNothing() {
answers.add(new DoesNothing());
return this;
}
public Stubber doAnswer(Answer answer) {
answers.add(answer);
return this;
}
public BDDStubberImpl(Stubber mockitoStubber) {
this.mockitoStubber = mockitoStubber;
}