改造测试,回调?

Retrofit testing, callbacks?

我正在尽最大努力学习如何正确测试我的 Android 应用程序。现在我通常使用以下结构:

在我自己处理线程之前,我已经测试过应用程序。在这种情况下,我不知道如何验证我的包装器是否真的在调用事件发布方法,因为这些方法是在回调上调用的。我该怎么做才能解决这个问题?

我能想到的唯一解决方案是不使用回调,但它们非常方便。为了测试而自己动手不是退步吗?

我只能猜测我的架构方式不适合测试。

编辑:这个问题表明将测试拆分为一个好主意:

1.- Test that your async process is submitted properly. You can mock the object that accepts your async requests and make sure that the submitted job has correct properties, etc. 2.- Test that your async callbacks are doing the right things. Here you can mock out the originally submitted job and assume it's initialized properly and verify that your callbacks are correct.

但是我如何在不模拟 Retrofit 服务的情况下测试第一部分(因为永远不应该模拟第三方代码)?

尝试将 Rx 与 Retrofit 结合使用。它使同步 Rx 请求成为异步的,从而避免了回调的需要。更重要的是,您可以从 Rx 机制获得完美的回调,这将帮助您正确测试。

调查RxJava with Retrofit

改造异步回调可以通过创建一个带有同步执行器的适配器来测试。

在适配器工厂中,我使用以下方法创建一个 Retrofit 适配器,用于使用 Robolectric 和 WireMock 进行测试。 WireMock 充当 baseURL 上的服务器,returns 通过 Retrofit 对 REST API 上的请求的响应。

public static RestAdapter synchronousAdapter(Context context, String baseUrl) {
    RestAdapter.Builder builder = initiateBuilder(context);
    builder.setEndpoint(baseUrl);
    Executor synchronous = new SynchronousExecutor();
    builder.setExecutors(synchronous, synchronous);
    return builder.build();
}

private static final class SynchronousExecutor implements Executor {
    @Override public void execute(Runnable r) {
        r.run();
    }
}