【问题标题】:unable to mock clientmethod returning Single<? extends HttpResponse> using Mockito无法模拟返回 Single<?使用 Mockito 扩展 HttpResponse>
【发布时间】:2019-02-11 15:33:09
【问题描述】:

我正在使用 Micronaut 构建一个微服务。这个特定的服务依赖于从另一个服务自动生成的客户端,我想在我的组件测试中模拟它。

但是我无法模拟 apiClient 的方法之一。它的签名是这样的:

    Single<? extends HttpResponse> patchProfile(String userId, UserprofileApiEntity userProfile);

其中HttpResponse 来自包io.micronaut.httpSingle 来自包io.reactivex

在我的测试中,我试图模拟这个端点:

        when(userProfileClientMock.patchProfile(userIdCaptor.capture(), profileCaptor.capture())).thenReturn(Single.just(HttpResponse.ok()));

但是我得到了错误

error: no suitable method found for thenReturn(Single<CAP#1>)
        when(userProfileClientMock.patchProfile(userIdCaptor.capture(), profileCaptor.capture())).thenReturn(response);
                                                                                                 ^
    method OngoingStubbing.thenReturn(Single<CAP#2>) is not applicable
      (argument mismatch; Single<CAP#1> cannot be converted to Single<CAP#2>)
    method OngoingStubbing.thenReturn(Single<CAP#2>,Single<CAP#2>...) is not applicable
      (argument mismatch; Single<CAP#1> cannot be converted to Single<CAP#2>)
  where CAP#1,CAP#2 are fresh type-variables:
    CAP#1 extends HttpResponse from capture of ? extends HttpResponse
    CAP#2 extends HttpResponse from capture of ? extends HttpResponse
Note: /home/anders/Documents/minecraft/minecraft.api.public.displaynames/minecraft.api.public.displaynames.server/src/test/java/net/minecraft/api/pub/displaynames/DisplaynamesApiTest.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

据我所知,这与签名的 &lt;? extends . . .&gt; 部分有关,我已经成功地模拟了来自类似 apiclients 的不同方法,返回诸如 Single&lt;Foo&gt;Maybe&lt;Bar&gt; 之类的东西 不幸的是,在这种情况下,更改客户端的签名没有意义。

我尝试将响应单指定为变量,将其显式键入为 Single&lt;? extends HttpResponse&gt;Single&lt;MutableHttpResponse&gt; 认为可能 mockito 以某种方式被类型擦除弄糊涂了,但无济于事。

任何想法可能是什么原因,以及如何解决它?

【问题讨论】:

    标签: java testing mockito rx-java2 micronaut


    【解决方案1】:

    所以我最终能够解决这个问题,使用不同的模拟语法,即

    doReturn(foo).when(bazMock).barMethod();
    

    这种模拟方式不提供类型安全性,这是一种权衡,但这似乎是一种必要的弊端。我猜这适用于您想要模拟返回泛型类的任何情况,类型为foo&lt;? extends bar&gt;

    【讨论】:

    • 这比使 Single 泛型好还是坏?我在 CryptoResult 中遇到了同样的问题,也可以通过将其归类为 CryptoResult 来解决。至少有顶级类的类型保护。我不知道这是前进还是后退。
    • 不确定您的意思? Single 已经是一个通用类。您的意思是删除实际方法的类型以便在测试中提供类型安全吗?我想在某些情况下这可能是有意义的,但是在 Single 的情况下,它只会从您的实际程序中删除 typsafety 并且基本上不会向您的测试添加任何内容,因为 Single 基本上只是意味着结果将被异步返回。
    猜你喜欢
    • 2019-01-28
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    相关资源
    最近更新 更多