模拟接口与类



我有一个接口定义如下:

public interface HttpClient {
    public <T> UdemyResponse<T> get(Request request,
      JSONUnmarshaler<T> unmarshaller, Gson gson)
      throws UdemyException, IOException;
}

我有一个实现接口的类:

public class OkHttp implements HttpClient {
public OkHttpClient client;
final Logger logger = LoggerFactory.getLogger(getClass());
public OkHttp() {
    this.client = new OkHttpClient();
}
@Override
public <T> UdemyResponse<T> get(Request request, JSONUnmarshaler<T> unmarshaller, Gson gson)
        throws UdemyException, IOException {
int status_code = 0;
        String next = null;
        String rawJSON = null;
        JsonElement jsonelement = null;
    Boolean retry = true;
    int attempts = 3;
    while ((attempts >= 0) && (retry) && status_code != 200) {
        try {
            Response response = this.client.newCall(request).execute();
            rawJSON = response.body().string();
            jsonelement = gson.fromJson(rawJSON, JsonElement.class);
            next = gson.fromJson(jsonelement.getAsJsonObject().get("next"), String.class);
            status_code = response.code();
            if (status_code == 401) {
                try {
                    logger.warn("token expired");
                    TimeUnit.SECONDS.sleep(5);
                    retry = true;
                    continue;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if ((status_code / 100) == 5) {
                logger.warn("gateway error");
                retry = true;
                continue;
            }
        } catch (IOException e) {
            e.printStackTrace();
            // this exception will be propagated to the main method and handled there to exit the program,
            // this exception should end the program.
            throw e;
        }
        attempts -= 1;
        retry = false;
    }   
    if (status_code != 200) {
        throw new UdemyException();
    }
    return new UdemyResponse<T>(status_code, next, rawJSON,
            unmarshaller.fromJSON(gson, jsonelement.getAsJsonObject()));
}

如果我模拟我的接口,我可以为 get() 方法编写测试用例,但我的 get() 方法使用 this.client,我也需要模拟该对象。

在这种情况下,模拟 OkHttp 对象比模拟接口更好吗?

如果你试图测试 get(),那么你不应该嘲笑那个方法,如果你这样做了,你正在测试什么?你需要模拟 get() 的其他依赖项来帮助你单独测试它。在这种情况下,如果 this.client 是 get() 的依赖项,这就是你需要模拟的。

根据问题更改进行编辑

这太可怕了:(status_code / 100).在那里测试真实状态代码。

您应该执行以下操作:

  1. 创建模拟OkHttpClient
  2. 使用反射将模拟注入到测试类中。
  3. 测试get方法。

你可能想在下面的代码中改变对ok事物的模拟,但你应该能够只使用简单的 Mockito 模拟来做所有事情。下面是一些示例代码:

public class TestOkHttp
{
  private static final String VALUE_JSON_STRING "some JSON string for your test";
  private OkHttp classToTest;
  @Mock
  private ClassWithExecute mockClassWithExecute;
  @Mock
  private OkHttpClient mockOkHttpClient;
  @Mock
  private Response mockResponse;
  @Mock
  private ResponseBodyClass mockResponseBodyClass;
  @Mock
  private Request mockRequest;
  private Gson testGson;
  @Test
  public void get_describeTheTest_expectedResults()
  {
    final JSONUnmarshaler<someclass> unmarshallerForThisTest = new JSONUnmarshaler<>()
    // setup the mocking functionality for this test.
    doReturn(desiredStatusCode).when(mockResponse).code();

    classToTest.get()
  }
  @Before
  public void preTestSetup()
  {
    MockitoAnnotations.initMocks(this);
    classToTest = new OkHttp();
    testGson = new Gson();
    doReturn(mockResponse).when(mockClassWithExecute).execute();
    doReturn(mockClassWithExecute).when(mockOkHttpClient).newCall(mockRequest);
    doReturn(mockResponseBodyClass).when(mockResponse).body();
    doReturn(VALUE_JSON_STRING).when(mockResponseBodyClass).string();
    ReflectionTestUtils.setField(classToTest,
      "client",
      mockOkHttpClient);
  }
}

相关内容

  • 没有找到相关文章

最新更新