org.mockito.internal.stubbing.answers.ThrowsException#org.mockito.stubbing.Stubber源码实例Demo

下面列出了org.mockito.internal.stubbing.answers.ThrowsException#org.mockito.stubbing.Stubber 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hadoop   文件: MockitoUtil.java
/**
 * 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();
    }
  });
}
 
源代码2 项目: joal   文件: ClientTest.java
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;
}
 
源代码3 项目: big-c   文件: MockitoUtil.java
/**
 * 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;
    }
  });
}
 
源代码6 项目: emodb   文件: DataStoreJerseyTest.java
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;
        }
    });
}
 
源代码7 项目: emodb   文件: DataStoreJerseyTest.java
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;
        }
    });
}
 
源代码8 项目: lambda-behave   文件: Expect.java
@SuppressWarnings("unchecked")
public <T> Stubber toAnswer(final Runnable method) {
    return Mockito.doAnswer(invocation -> {
        Object[] arguments = invocation.getArguments();
        method.run();
        return null;
    });
}
 
源代码9 项目: lambda-behave   文件: Expect.java
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;
    });
}
 
源代码10 项目: hadoop   文件: TestQuorumJournalManager.java
private Stubber injectIOE() {
  return futureThrows(new IOException("Injected"));
}
 
源代码11 项目: hadoop   文件: TestQuorumJournalManagerUnit.java
static <V> Stubber futureReturns(V value) {
  ListenableFuture<V> ret = Futures.immediateFuture(value);
  return Mockito.doReturn(ret);
}
 
源代码12 项目: hadoop   文件: TestQuorumJournalManagerUnit.java
static Stubber futureThrows(Throwable t) {
  ListenableFuture<?> ret = Futures.immediateFailedFuture(t);
  return Mockito.doReturn(ret);
}
 
源代码13 项目: big-c   文件: TestQuorumJournalManager.java
private Stubber injectIOE() {
  return futureThrows(new IOException("Injected"));
}
 
源代码14 项目: big-c   文件: TestQuorumJournalManagerUnit.java
static <V> Stubber futureReturns(V value) {
  ListenableFuture<V> ret = Futures.immediateFuture(value);
  return Mockito.doReturn(ret);
}
 
源代码15 项目: big-c   文件: TestQuorumJournalManagerUnit.java
static Stubber futureThrows(Throwable t) {
  ListenableFuture<?> ret = Futures.immediateFailedFuture(t);
  return Mockito.doReturn(ret);
}
 
源代码16 项目: zeppelin   文件: KSQLInterpreterTest.java
@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();
}
 
源代码17 项目: zeppelin   文件: KSQLInterpreterTest.java
@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());
}
 
源代码18 项目: mockito-java8   文件: WithMockito.java
/**
 * Delegates call to {@link Mockito#doThrow(Throwable...)}.
 */
default Stubber doThrow(Throwable... toBeThrown) {
    return Mockito.doThrow(toBeThrown);
}
 
源代码19 项目: mockito-java8   文件: WithMockito.java
/**
 * Delegates call to {@link Mockito#doThrow(Class)}.
 */
default Stubber doThrow(Class<? extends Throwable> toBeThrown) {
    return Mockito.doThrow(toBeThrown);
}
 
源代码20 项目: mockito-java8   文件: WithMockito.java
/**
 * Delegates call to {@link Mockito#doCallRealMethod()}.
 */
default Stubber doCallRealMethod() {
    return Mockito.doCallRealMethod();
}
 
源代码21 项目: mockito-java8   文件: WithMockito.java
/**
 * Delegates call to {@link Mockito#doAnswer(Answer)}.
 */
default Stubber doAnswer(Answer answer) {
    return Mockito.doAnswer(answer);
}
 
源代码22 项目: mockito-java8   文件: WithMockito.java
/**
 * Delegates call to {@link Mockito#doNothing()}.
 */
default Stubber doNothing() {
    return Mockito.doNothing();
}
 
源代码23 项目: mockito-java8   文件: WithMockito.java
/**
 * Delegates call to {@link Mockito#doReturn(Object)}.
 */
default Stubber doReturn(Object toBeReturned) {
    return Mockito.doReturn(toBeReturned);
}
 
源代码24 项目: mockito-java8   文件: WithMockito.java
/**
 * Delegates call to {@link Mockito#doReturn(Object, Object...)}.
 */
default Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {
    return Mockito.doReturn(toBeReturned, toBeReturnedNext);
}
 
源代码25 项目: astor   文件: MockitoCore.java
public Stubber doAnswer(Answer answer) {
    mockingProgress.stubbingStarted();
    mockingProgress.resetOngoingStubbing();
    return new StubberImpl().doAnswer(answer);
}
 
源代码26 项目: astor   文件: StubberImpl.java
public Stubber doReturn(Object toBeReturned) {
    answers.add(new Returns(toBeReturned));
    return this;
}
 
源代码27 项目: astor   文件: StubberImpl.java
public Stubber doThrow(Throwable toBeThrown) {
    answers.add(new ThrowsException(toBeThrown));
    return this;
}
 
源代码28 项目: astor   文件: StubberImpl.java
public Stubber doNothing() {
    answers.add(new DoesNothing());
    return this;
}
 
源代码29 项目: astor   文件: StubberImpl.java
public Stubber doAnswer(Answer answer) {
    answers.add(answer);
    return this;
}
 
源代码30 项目: astor   文件: BDDMockito.java
public BDDStubberImpl(Stubber mockitoStubber) {
    this.mockitoStubber = mockitoStubber;
}