【问题标题】:Mockito: using when over a mocked Mono with timeout method causes InvalidUseOfMatchersExceptionMockito:在具有超时方法的模拟 Mono 上使用时会导致 InvalidUseOfMatchersException
【发布时间】:2022-10-20 20:33:03
【问题描述】:

我正在对反应式 WebClient 使用进行单元测试,当我尝试使用方法 timeout(Duration d) 模拟 Mono 的行为时,我的问题就出现了。

我只想控制调用的结果,例如:

private Mono<String> withTimeout(Mono<String> myMono) {
  return myMono.timeout(Duration.of(globalDuration));
}

所以我正在使用这个:

@Test
void test() {
...
    Mono<String> monoMock = (Mono<String>) Mockito.mock(Mono.class);
    when(monoMock.timeout(Mockito.any(Duration.class))).thenReturn(Mono.just("OK"));
...
}

但它会产生一个

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaces or misused argument matcher detected here:

-> at service.UserServiceTest.test(UserServiceTest.java:98)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is retur....

我应该怎么做什么时候这个结果Mono.timeout方法?

【问题讨论】:

    标签: mockito spring-webclient


    【解决方案1】:

    我也刚刚遇到了这个奇怪的错误,除了你的错误我还得到了java.lang.NullPointerException

    我能够通过导入来解决这个问题:

    <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-inline</artifactId>
            <version>4.8.1</version>
        </dependency>
    

    在此之后,我能够简单地做到这一点而没有任何问题:

    var monoMock = Mockito.mock(Mono.class);
    lenient().when(monoMock.timeout((any(Duration.class)))).thenReturn(monoMock);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多