org.mockito.Mockito.verifyNoMoreInteractions()方法的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(10.6k)|赞(0)|评价(0)|浏览(388)

本文整理了Java中org.mockito.Mockito.verifyNoMoreInteractions()方法的一些代码示例,展示了Mockito.verifyNoMoreInteractions()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Mockito.verifyNoMoreInteractions()方法的具体详情如下:
包路径:org.mockito.Mockito
类名称:Mockito
方法名:verifyNoMoreInteractions

Mockito.verifyNoMoreInteractions介绍

[英]Checks if any of given mocks has any unverified interaction.

You can use this method after you verified your mocks - to make sure that nothing else was invoked on your mocks.

See also Mockito#never() - it is more explicit and communicates the intent well.

Stubbed invocations (if called) are also treated as interactions.

A word of warning: Some users who did a lot of classic, expect-run-verify mocking tend to use verifyNoMoreInteractions() very often, even in every test method. verifyNoMoreInteractions() is not recommended to use in every test method. verifyNoMoreInteractions() is a handy assertion from the interaction testing toolkit. Use it only when it's relevant. Abusing it leads to overspecified, less maintainable tests. You can find further reading here.

This method will also detect unverified invocations that occurred before the test method, for example: in setUp(), @Before method or in constructor. Consider writing nice code that makes interactions only in test methods.

Example:

//interactions 
mock.doSomething(); 
mock.doSomethingUnexpected(); 
//verification 
verify(mock).doSomething(); 
//following will fail because 'doSomethingUnexpected()' is unexpected 
verifyNoMoreInteractions(mock);

See examples in javadoc for Mockito class
[中]检查是否有任何给定的模拟具有任何未验证的交互。
您可以在验证模拟后使用此方法,以确保没有在模拟上调用任何其他内容。
另请参见Mockito#never()-它更明确,能够很好地传达意图。
存根调用(如果被调用)也被视为交互。
警告:一些做了很多经典的expect run verify模拟的用户倾向于经常使用verifyNoMoreInteractions(),即使在每个测试方法中也是如此。不建议在每种测试方法中使用verifyNoMoreInteractions()verifyNoMoreInteractions()是来自交互测试工具包的一个方便的断言。只有在相关的时候才使用它。滥用它会导致过度指定、不易维护的测试。您可以进一步阅读here
此方法还将检测在测试方法之前发生的未经验证的调用,例如setUp()@Before方法或构造函数中的调用。考虑编写好代码,只在测试方法中进行交互。
例子:

//interactions 
mock.doSomething(); 
mock.doSomethingUnexpected(); 
//verification 
verify(mock).doSomething(); 
//following will fail because 'doSomethingUnexpected()' is unexpected 
verifyNoMoreInteractions(mock);

请参阅javadoc中Mockito类的示例

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Test
public void handleReturnValueWithMultipleHandlers() throws Exception {
  HandlerMethodReturnValueHandler anotherIntegerHandler = mock(HandlerMethodReturnValueHandler.class);
  when(anotherIntegerHandler.supportsReturnType(this.integerType)).thenReturn(true);
  this.handlers.handleReturnValue(55, this.integerType, this.mavContainer, null);
  verify(this.integerHandler).handleReturnValue(55, this.integerType, this.mavContainer, null);
  verifyNoMoreInteractions(anotherIntegerHandler);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void afterConnectFailure() {
  IllegalStateException exception = new IllegalStateException("simulated exception");
  this.session.afterConnectFailure(exception);
  verify(this.sessionHandler).handleTransportError(this.session, exception);
  verifyNoMoreInteractions(this.sessionHandler);
}

代码示例来源:origin: ReactiveX/RxJava

private static void verifyObserver(Observer<Integer> mock, int numSubscriptions, int numItemsExpected, Throwable error) {
  verify(mock, times(numItemsExpected)).onNext((Integer) notNull());
  verify(mock, times(numSubscriptions)).onError(error);
  verifyNoMoreInteractions(mock);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void handleMessageEmptyPayload() throws Exception {
  this.session.handleMessage(new TextMessage(""), this.webSocketSession);
  verifyNoMoreInteractions(this.webSocketHandler);
}

代码示例来源:origin: spring-projects/spring-framework

private WebSocketHandler connect() {
  this.stompClient.connect("/foo", mock(StompSessionHandler.class));
  verify(this.stompSession).getSessionFuture();
  verifyNoMoreInteractions(this.stompSession);
  WebSocketHandler webSocketHandler = this.webSocketHandlerCaptor.getValue();
  assertNotNull(webSocketHandler);
  return webSocketHandler;
}

代码示例来源:origin: spring-projects/spring-framework

@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void cancelInactivityTasks() throws Exception {
  TcpConnection<byte[]> tcpConnection = getTcpConnection();
  ScheduledFuture future = mock(ScheduledFuture.class);
  when(this.taskScheduler.scheduleWithFixedDelay(any(), eq(1L))).thenReturn(future);
  tcpConnection.onReadInactivity(mock(Runnable.class), 2L);
  tcpConnection.onWriteInactivity(mock(Runnable.class), 2L);
  this.webSocketHandlerCaptor.getValue().afterConnectionClosed(this.webSocketSession, CloseStatus.NORMAL);
  verify(future, times(2)).cancel(true);
  verifyNoMoreInteractions(future);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void handleFailure() {
  IllegalStateException exception = new IllegalStateException("simulated exception");
  this.session.handleFailure(exception);
  verify(this.sessionHandler).handleTransportError(this.session, exception);
  verifyNoMoreInteractions(this.sessionHandler);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void handleWebSocketMessagePong() throws Exception {
  connect().handleMessage(this.webSocketSession, new PongMessage());
  verifyNoMoreInteractions(this.stompSession);
}

代码示例来源:origin: google/guava

@GwtIncompatible // Mockito
public void testOnSuccessThrowsRuntimeException() throws Exception {
 RuntimeException exception = new RuntimeException();
 String result = "result";
 SettableFuture<String> future = SettableFuture.create();
 @SuppressWarnings("unchecked") // Safe for a mock
 FutureCallback<String> callback = Mockito.mock(FutureCallback.class);
 addCallback(future, callback, directExecutor());
 Mockito.doThrow(exception).when(callback).onSuccess(result);
 future.set(result);
 assertEquals(result, future.get());
 Mockito.verify(callback).onSuccess(result);
 Mockito.verifyNoMoreInteractions(callback);
}

代码示例来源:origin: ReactiveX/RxJava

private static void verifyObserver(Subscriber<Integer> mock, int numSubscriptions, int numItemsExpected, Throwable error) {
  verify(mock, times(numItemsExpected)).onNext((Integer) notNull());
  verify(mock, times(numSubscriptions)).onError(error);
  verifyNoMoreInteractions(mock);
}

代码示例来源:origin: spring-projects/spring-framework

@SuppressWarnings("unchecked")
@Test
public void startAndStopWithHeartbeatValue() {
  ScheduledFuture future = mock(ScheduledFuture.class);
  when(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), eq(15000L))).thenReturn(future);
  this.messageHandler.setTaskScheduler(this.taskScheduler);
  this.messageHandler.setHeartbeatValue(new long[] {15000, 16000});
  this.messageHandler.start();
  verify(this.taskScheduler).scheduleWithFixedDelay(any(Runnable.class), eq(15000L));
  verifyNoMoreInteractions(this.taskScheduler, future);
  this.messageHandler.stop();
  verify(future).cancel(true);
  verifyNoMoreInteractions(future);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void afterConnectionClosed() {
  this.session.afterConnectionClosed();
  verify(this.sessionHandler).handleTransportError(same(this.session), any(ConnectionLostException.class));
  verifyNoMoreInteractions(this.sessionHandler);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void uriBuilderWithPathOverride() {
  this.builder.build().get()
      .uri(builder -> builder.replacePath("/path").build())
      .exchange();
  ClientRequest request = verifyAndGetRequest();
  assertEquals("/path", request.url().toString());
  verifyNoMoreInteractions(this.exchangeFunction);
}

代码示例来源:origin: google/guava

public void testStandardValues() throws InvocationTargetException {
 @SuppressWarnings("unchecked")
 final Map<String, Boolean> map = mock(Map.class);
 Map<String, Boolean> forward =
   new ForwardingMap<String, Boolean>() {
    @Override
    protected Map<String, Boolean> delegate() {
     return map;
    }
    @Override
    public Collection<Boolean> values() {
     return new StandardValues();
    }
   };
 callAllPublicMethods(new TypeToken<Collection<Boolean>>() {}, forward.values());
 // These are the methods specified by StandardValues
 verify(map, atLeast(0)).clear();
 verify(map, atLeast(0)).containsValue(anyObject());
 verify(map, atLeast(0)).isEmpty();
 verify(map, atLeast(0)).size();
 verify(map, atLeast(0)).entrySet();
 verifyNoMoreInteractions(map);
}

代码示例来源:origin: ReactiveX/RxJava

private static void verifyObserverMock(Subscriber<Integer> mock, int numSubscriptions, int numItemsExpected) {
  verify(mock, times(numItemsExpected)).onNext((Integer) notNull());
  verify(mock, times(numSubscriptions)).onComplete();
  verifyNoMoreInteractions(mock);
}

代码示例来源:origin: spring-projects/spring-framework

@SuppressWarnings("unchecked")
@Test
public void brokerUnavailableEvent() throws Exception {
  ScheduledFuture future = Mockito.mock(ScheduledFuture.class);
  when(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), any(Long.class))).thenReturn(future);
  BrokerAvailabilityEvent event = new BrokerAvailabilityEvent(true, this);
  this.handler.onApplicationEvent(event);
  verifyNoMoreInteractions(future);
  event = new BrokerAvailabilityEvent(false, this);
  this.handler.onApplicationEvent(event);
  verify(future).cancel(true);
}

代码示例来源:origin: ReactiveX/RxJava

@Test
public void shouldAllowToThrowCheckedException() {
  final Exception checkedException = new Exception("test exception");
  Flowable<Object> fromCallableFlowable = Flowable.fromCallable(new Callable<Object>() {
    @Override
    public Object call() throws Exception {
      throw checkedException;
    }
  });
  Subscriber<Object> subscriber = TestHelper.mockSubscriber();
  fromCallableFlowable.subscribe(subscriber);
  verify(subscriber).onSubscribe(any(Subscription.class));
  verify(subscriber).onError(checkedException);
  verifyNoMoreInteractions(subscriber);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void uriBuilder() {
  this.builder.build().get()
      .uri(builder -> builder.path("/path").queryParam("q", "12").build())
      .exchange();
  ClientRequest request = verifyAndGetRequest();
  assertEquals("/base/path?q=12", request.url().toString());
  verifyNoMoreInteractions(this.exchangeFunction);
}

代码示例来源:origin: google/guava

@GwtIncompatible // Mockito
public void testOnSuccessThrowsError() throws Exception {
 class TestError extends Error {}
 TestError error = new TestError();
 String result = "result";
 SettableFuture<String> future = SettableFuture.create();
 @SuppressWarnings("unchecked") // Safe for a mock
 FutureCallback<String> callback = Mockito.mock(FutureCallback.class);
 addCallback(future, callback, directExecutor());
 Mockito.doThrow(error).when(callback).onSuccess(result);
 try {
  future.set(result);
  fail("Should have thrown");
 } catch (TestError e) {
  assertSame(error, e);
 }
 assertEquals(result, future.get());
 Mockito.verify(callback).onSuccess(result);
 Mockito.verifyNoMoreInteractions(callback);
}

代码示例来源:origin: ReactiveX/RxJava

private static void verifyObserverMock(Observer<Integer> mock, int numSubscriptions, int numItemsExpected) {
  verify(mock, times(numItemsExpected)).onNext((Integer) notNull());
  verify(mock, times(numSubscriptions)).onComplete();
  verifyNoMoreInteractions(mock);
}

相关文章