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

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

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

Mockito.when介绍

[英]Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.

Simply put: "When the x method is called then return y".

Examples:

when(mock.someMethod()).thenReturn(10); 
//you can use flexible argument matchers, e.g: 
when(mock.someMethod(anyString())).thenReturn(10); 
//setting exception to be thrown: 
when(mock.someMethod("some arg")).thenThrow(new RuntimeException()); 
//you can set different behavior for consecutive method calls. 
//Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls. 
when(mock.someMethod("some arg")) 
.thenThrow(new RuntimeException()) 
.thenReturn("foo"); 
//Alternative, shorter version for consecutive stubbing: 
when(mock.someMethod("some arg")) 
.thenReturn("one", "two"); 
//is the same as: 
when(mock.someMethod("some arg")) 
.thenReturn("one") 
.thenReturn("two"); 
//shorter version for consecutive method calls throwing exceptions: 
when(mock.someMethod("some arg")) 
.thenThrow(new RuntimeException(), new NullPointerException();

For stubbing void methods with throwables see: Mockito#doThrow(Throwable...)

Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override it. Please note that overridding stubbing is a potential code smell that points out too much stubbing.

Once stubbed, the method will always return stubbed value regardless of how many times it is called.

Last stubbing is more important - when you stubbed the same method with the same arguments many times.

Although it is possible to verify a stubbed invocation, usually it's just redundant. Let's say you've stubbed foo.bar(). If your code cares what foo.bar() returns then something else breaks(often before even verify() gets executed). If your code doesn't care what get(0) returns then it should not be stubbed. Not convinced? See here.

See examples in javadoc for Mockito class
[中]启用存根方法。当您希望模拟在调用特定方法时返回特定值时,可以使用它。
简单地说:“当调用x方法时,返回y”。
示例:

when(mock.someMethod()).thenReturn(10); 
//you can use flexible argument matchers, e.g: 
when(mock.someMethod(anyString())).thenReturn(10); 
//setting exception to be thrown: 
when(mock.someMethod("some arg")).thenThrow(new RuntimeException()); 
//you can set different behavior for consecutive method calls. 
//Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls. 
when(mock.someMethod("some arg")) 
.thenThrow(new RuntimeException()) 
.thenReturn("foo"); 
//Alternative, shorter version for consecutive stubbing: 
when(mock.someMethod("some arg")) 
.thenReturn("one", "two"); 
//is the same as: 
when(mock.someMethod("some arg")) 
.thenReturn("one") 
.thenReturn("two"); 
//shorter version for consecutive method calls throwing exceptions: 
when(mock.someMethod("some arg")) 
.thenThrow(new RuntimeException(), new NullPointerException();

有关使用可丢弃的存根无效方法,请参见:Mockito#doThrow(可丢弃…)
可以覆盖存根:例如,普通存根可以转到夹具设置,但测试方法可以覆盖它。请注意,重写存根是一种潜在的代码气味,指出了太多的存根。
一旦存根,无论调用多少次,该方法都将始终返回存根值。
最后一个存根更重要——当您多次使用相同的参数存根相同的方法时。
虽然可以验证存根调用,但通常它只是冗余的。假设您已存根foo.bar()。如果您的代码关心foo.bar()返回的内容,那么其他内容就会中断(通常在verify()执行之前)。如果您的代码不关心get(0)返回的内容,则不应将其存根。不相信?见here
有关Mockito类,请参见javadoc中的示例

代码示例

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

@SuppressWarnings("unchecked")
@Test
public void shouldNotInvokeFuncUntilSubscription() throws Exception {
  Callable<Object> func = mock(Callable.class);
  when(func.call()).thenReturn(new Object());
  Single<Object> fromCallableSingle = Single.fromCallable(func);
  verifyZeroInteractions(func);
  fromCallableSingle.subscribe();
  verify(func).call();
}

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

@Override
protected void setUp() throws Exception {
 super.setUp();
 hasher = mock(Hasher.class);
 hashFunction = mock(HashFunction.class);
 when(hashFunction.newHasher()).thenReturn(hasher);
}

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

public void testAddDelayedShutdownHook_interrupted() throws InterruptedException {
 TestApplication application = new TestApplication();
 ExecutorService service = mock(ExecutorService.class);
 application.addDelayedShutdownHook(service, 2, TimeUnit.SECONDS);
 when(service.awaitTermination(2, TimeUnit.SECONDS)).thenThrow(new InterruptedException());
 application.shutdown();
 verify(service).shutdown();
}

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

@Test
public void testCancelledBeforeSubscribe() throws Exception {
  @SuppressWarnings("unchecked")
  Future<Object> future = mock(Future.class);
  CancellationException e = new CancellationException("unit test synthetic cancellation");
  when(future.get()).thenThrow(e);
  Observer<Object> o = TestHelper.mockObserver();
  TestObserver<Object> to = new TestObserver<Object>(o);
  to.dispose();
  Observable.fromFuture(future).subscribe(to);
  to.assertNoErrors();
  to.assertNotComplete();
}

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

@SuppressWarnings("unchecked")
@Test
public void shouldNotInvokeFuncUntilSubscription() throws Exception {
  Callable<Object> func = mock(Callable.class);
  when(func.call()).thenReturn(new Object());
  Observable<Object> fromCallableObservable = Observable.fromCallable(func);
  verifyZeroInteractions(func);
  fromCallableObservable.subscribe();
  verify(func).call();
}

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

@Test
public void testCancelledBeforeSubscribe() throws Exception {
  @SuppressWarnings("unchecked")
  Future<Object> future = mock(Future.class);
  CancellationException e = new CancellationException("unit test synthetic cancellation");
  when(future.get()).thenThrow(e);
  Subscriber<Object> subscriber = TestHelper.mockSubscriber();
  TestSubscriber<Object> ts = new TestSubscriber<Object>(subscriber);
  ts.dispose();
  Flowable.fromFuture(future).subscribe(ts);
  ts.assertNoErrors();
  ts.assertNotComplete();
}

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

@Override
protected void setUp() throws Exception {
 super.setUp();
 hasher = mock(Hasher.class);
 hashFunction = mock(HashFunction.class);
 buffer = new ByteArrayInputStream(testBytes);
 when(hashFunction.newHasher()).thenReturn(hasher);
}

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

@SuppressWarnings("unchecked")
@Test
public void shouldNotInvokeFuncUntilSubscription() throws Exception {
  Callable<Object> func = mock(Callable.class);
  when(func.call()).thenReturn(new Object());
  Flowable<Object> fromCallableFlowable = Flowable.fromCallable(func);
  verifyZeroInteractions(func);
  fromCallableFlowable.subscribe();
  verify(func).call();
}

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

@SuppressWarnings("unchecked")
@Override
protected void setUp() {
 backingMap = mock(ConcurrentMap.class);
 when(backingMap.isEmpty()).thenReturn(true);
 multiset = new ConcurrentHashMultiset<>(backingMap);
}

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

public void testShutdownAndAwaitTermination_immediateShutdownInternal() throws Exception {
 ExecutorService service = mock(ExecutorService.class);
 when(service.awaitTermination(HALF_SECOND_NANOS, NANOSECONDS)).thenReturn(true);
 when(service.isTerminated()).thenReturn(true);
 assertTrue(shutdownAndAwaitTermination(service, 1L, SECONDS));
 verify(service).shutdown();
 verify(service).awaitTermination(HALF_SECOND_NANOS, NANOSECONDS);
}

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

private <T> HandlerMethodArgumentResolver stubResolver(Mono<Object> stubValue) {
  HandlerMethodArgumentResolver resolver = mock(HandlerMethodArgumentResolver.class);
  when(resolver.supportsParameter(any())).thenReturn(true);
  when(resolver.resolveArgument(any(), any(), any())).thenReturn(stubValue);
  return resolver;
}

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

public void testShutdownAndAwaitTermination_forcedShutDownInternal() throws Exception {
 ExecutorService service = mock(ExecutorService.class);
 when(service.awaitTermination(HALF_SECOND_NANOS, NANOSECONDS))
   .thenReturn(false)
   .thenReturn(true);
 when(service.isTerminated()).thenReturn(true);
 assertTrue(shutdownAndAwaitTermination(service, 1L, SECONDS));
 verify(service).shutdown();
 verify(service, times(2)).awaitTermination(HALF_SECOND_NANOS, NANOSECONDS);
 verify(service).shutdownNow();
}

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

@Before
public void setup() {
  when(this.client.getWebConnection()).thenReturn(mock(WebConnection.class));
  this.builder = new MockMvcWebConnectionBuilderSupport(this.wac) {};
}

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

public void testShutdownAndAwaitTermination_nonTerminationInternal() throws Exception {
 ExecutorService service = mock(ExecutorService.class);
 when(service.awaitTermination(HALF_SECOND_NANOS, NANOSECONDS))
   .thenReturn(false)
   .thenReturn(false);
 assertFalse(shutdownAndAwaitTermination(service, 1L, SECONDS));
 verify(service).shutdown();
 verify(service, times(2)).awaitTermination(HALF_SECOND_NANOS, NANOSECONDS);
 verify(service).shutdownNow();
}

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

@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  WebSocketClient webSocketClient = mock(WebSocketClient.class);
  this.stompClient = new TestWebSocketStompClient(webSocketClient);
  this.stompClient.setTaskScheduler(this.taskScheduler);
  this.stompClient.setStompSession(this.stompSession);
  this.webSocketHandlerCaptor = ArgumentCaptor.forClass(WebSocketHandler.class);
  this.handshakeFuture = new SettableListenableFuture<>();
  when(webSocketClient.doHandshake(this.webSocketHandlerCaptor.capture(), any(), any(URI.class)))
      .thenReturn(this.handshakeFuture);
}

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

@Test
public void attribute() {
  String name = "foo";
  String value = "bar";
  when(mockRequest.attribute(name)).thenReturn(Optional.of(value));
  assertEquals(Optional.of(value), wrapper.attribute(name));
}

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

@Before
public void setup() {
  this.protocolHandler = new StompSubProtocolHandler();
  this.channel = Mockito.mock(MessageChannel.class);
  this.messageCaptor = ArgumentCaptor.forClass(Message.class);
  when(this.channel.send(any())).thenReturn(true);
  this.session = new TestWebSocketSession();
  this.session.setId("s1");
  this.session.setPrincipal(new TestPrincipal("joe"));
}

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

@Test
public void queryParam() {
  String name = "foo";
  String value = "bar";
  when(mockRequest.queryParam(name)).thenReturn(Optional.of(value));
  assertEquals(Optional.of(value), wrapper.queryParam(name));
}

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

@Test
public void getUserFromLocalRegistry() throws Exception {
  SimpUser user = Mockito.mock(SimpUser.class);
  Set<SimpUser> users = Collections.singleton(user);
  when(this.localRegistry.getUsers()).thenReturn(users);
  when(this.localRegistry.getUserCount()).thenReturn(1);
  when(this.localRegistry.getUser("joe")).thenReturn(user);
  assertEquals(1, this.registry.getUserCount());
  assertSame(user, this.registry.getUser("joe"));
}

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

@SuppressWarnings("unchecked")
@Test
public void shouldCallOnNextAndOnCompleted() throws Exception {
  Callable<String> func = mock(Callable.class);
  when(func.call()).thenReturn("test_value");
  Observable<String> fromCallableObservable = Observable.fromCallable(func);
  Observer<Object> observer = TestHelper.mockObserver();
  fromCallableObservable.subscribe(observer);
  verify(observer).onNext("test_value");
  verify(observer).onComplete();
  verify(observer, never()).onError(any(Throwable.class));
}

相关文章