且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何等待Okhttp调用的结果在测试中使用它?

更新时间:2023-01-18 14:08:06

我认为这里可能发生的是您正在异步执行OkHttp调用,因此您要在任务完成之前点击return语句.为了测试,可以同步进行OkHttp调用吗?您可以使用下面显示的response.isSuccessful处理成功/失败案例.

I think what may be happening here is you're performing the OkHttp call asynchronously, so you're hitting the return statement before the task is complete. For the sake of the test would it be possible to do the OkHttp call synchronously? You can handle the success/failure case with response.isSuccessful seen below.

   private final OkHttpClient client = new OkHttpClient();

   public void run() throws Exception {
       Request request = new Request.Builder()
           .url("your_url_here")
           .build();

       Response response = client.newCall(request).execute();
       if(response.isSuccessful()){
           return true;             
        }else return false;

    }