【问题标题】:How to mock a retrofit2 error response with Mockito thenReturn?如何使用 Mockito thenReturn 模拟改造 2 错误响应?
【发布时间】:2022-01-01 15:04:43
【问题描述】:

我有这段代码要测试:

public List<Map<String, Object>> getMaps (Query query) throws CustomException {
   Response<MapsResponse> response = mapsApi.get(); // this is a retrofit2 response
   if (!response.isSuccessful()) {
      handle(response); // throws CustomException
   }
   .
   .
   .
}

所以我用 mockito 模拟了它,但是当我尝试这样做时:

retrofit2.Response<MapsResponse> response = retrofit2.Response.error(500, ResponseBody.create(null, content))
when(mapsApi.get()).thenReturn(response);

它说它无法解析方法'thenReturn...'

有谁知道如何模拟会触发我的异常的错误响应(错误 HTTP 代码)?谢谢!

【问题讨论】:

  • 检查您的导入。好像你输入了错误的when。
  • 有人可以发布一个工作示例吗? (嘲笑改造 2 的回应)我想我会设法从那里修复它。

标签: java http mockito retrofit2 response


【解决方案1】:

我通常这样使用 Mockito

导入改造模拟

<dependency>
    <groupId>com.squareup.retrofit2</groupId>
    <artifactId>retrofit-mock</artifactId>
    <version>${version.retrofit}</version>
    <scope>test</scope>
</dependency>

创建和使用模拟

import retrofit2.mock.Calls;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mock;

...

Api api = mock(Api.class); // Mockito mock

...

when(api.doSomething(param)).thenReturn(Calls.response(response));

Retrofit Mock 仅用于生成响应。

我找到了this answer,希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 2016-03-04
    • 2020-05-25
    • 2020-05-14
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多