下面列出了org.mockito.Mockito#doAnswer ( ) 实例代码,或者点击链接到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();
}
});
}
/**
* 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();
}
});
}
@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;
});
}
@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#doAnswer(Answer)}.
*/
default Stubber doAnswer(Answer answer) {
return Mockito.doAnswer(answer);
}
/**
* Same as {@link Mockito#doAnswer(Answer)} but adds the ability to stub static method calls via
* {@link StaticCapableStubber#when(MockedMethod)} and
* {@link StaticCapableStubber#when(MockedVoidMethod)}.
*/
public static StaticCapableStubber doAnswer(Answer answer) {
return new StaticCapableStubber(Mockito.doAnswer(answer));
}