【问题标题】:Using MockWebServer 's dispatcher in espresso test to respond to an Async call from another module在 espresso 测试中使用 MockWebServer 的调度程序来响应来自另一个模块的 Async 调用
【发布时间】:2018-10-31 04:56:20
【问题描述】:

我正在为一个应用程序编写 UI 测试,该应用程序期望 JSON 有效负载作为对通过异步调用发出的请求的响应,该调用由我正在测试的活动中的按钮触发。我打算提供各种模拟有效负载来设置此活动的状态并在 UI 中声明各种项目。

我没有让调度程序捕获通过异步调用发出的请求。

异步调用是在模块内的一个类中进行的,这是我的应用程序的编译时依赖项,我觉得这是我的问题所在,甚至不确定这是否超出了 Espresso 的能力范围。

@Before
public void setup() throws Exception {
    server = new MockWebServer();
    server.start();
    // setting API in my production code to the MockWebServer 
    settingsProvider.setWebServiceURL(server.url("/").toString());

    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest recordedRequest) throws InterruptedException {

            if (recordedRequest.getPath().startsWith("/v1/customers")) {

                return new MockResponse().setResponseCode(200).setBody(JSONstring);
            }
            return new MockResponse().setResponseCode(204);
        }
    });
    }

如果我在实际测试中提出测试请求,它会起作用:

@Before
    public void testGet(){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(server.url("/v1/customers").toString()).build();
        Log.d(LOG_TAG, "Test send GET " + request);

        try {
            Response response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

通过添加日志,我已验证我的 API url 设置正确,并且与 MockWebServer 的端口相同。该应用当前未使用任何依赖注入。

异步调用的主要部分:

    public void makeAsyncCall(final Application ctx , final AsyncWebServiceRequest request, final ResponseListenerInterface rli){

    final AsyncWebServiceResponseListener listener = new AsyncWebServiceResponseListener(ctx, request, rli);

    IntentFilter responseIntent = new IntentFilter(CommsActions.SEND);
    responseIntent.addCategory(request.getMessageType());
    ctx.registerReceiver(listener, responseIntent);

    try {
               ctx.startService(intent);
    } catch (Exception e) {
        Log.e(LOG_TAG , Log.getStackTraceString(e));
        );
    }
}

感谢任何输入。

【问题讨论】:

    标签: android android-espresso mockwebserver


    【解决方案1】:

    长话短说 - 我没有意识到我实际上是在尝试模拟 AMQP 调用,菜鸟动作。

    幸运的是,我能够通过使用改造将这些代码转换为 HTTP 请求来简化代码,因为应用程序只需要通过 AMQP 执行数据发送,而检索可以是一个简单的 HTTP GET,它可以轻松实现 mockwebserver并实际上加快了请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 2019-07-23
      • 2019-07-10
      • 1970-01-01
      • 2012-05-19
      • 2017-04-22
      相关资源
      最近更新 更多