首页 > 解决方案 > 如何使用 OkHttp3 Post 请求为 android 制作单元测试代码?

问题描述

我已经实现了一个方法 - 在 LoginService 类中的 postData 如下所示 -

public class LoginService {


private String responsePost = "";
private String response_status;
private Context context;

String logInResponse;
private String account_token = "";

public LoginService(Context context) {
    this.context = context;
}


public void postData(String url, final String email, String password) {


    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    Map<String, String> params = new HashMap<String, String>();
    params.put("email", "" + email);
    params.put("password", "" + password);

    JSONObject parameter = new JSONObject(params);
    OkHttpClient client = new OkHttpClient();

    RequestBody body = RequestBody.create(JSON, parameter.toString());
    Request request = new Request.Builder()
            .url(url+"login")
            .post(body)
            .addHeader("content-type", "application/json; charset=utf-8")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {


            responsePost = response.code()+"";
            Log.e("###response_code:", responsePost);

            if(responsePost.equals("200"))
            {

                logInResponse="logged In";

                account_token = response.headers().get("Authorization");

                SharedPreferences.Editor editor = context.getSharedPreferences("Profile_PREF", MODE_PRIVATE).edit();
                editor.putString("account_id", account_token);
                editor.putString("email", email);
                editor.apply();

                Intent intent = new Intent(context, HomeActivity.class);

                context.startActivity(intent);
            }

            else
            {
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //show the response body
                        Toast.makeText(context,"Incorrent Email or Password", Toast.LENGTH_SHORT).show();
                    }
                });

            }


        }

    });



}

}

此方法的目的是在正文中发布电子邮件和密码后获得正确的响应代码。如果响应码匹配则登录成功,否则不成功。现在,我编写了一个测试类来测试 postData 方法,如下所示 -

public class LoginServiceTest {

private String responsePost = "";

@Test
public void postData() throws Exception {

    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    Map<String, String> params = new HashMap<String, String>();
    params.put("email", "a@a.a");
    params.put("password", "123456");

    JSONObject parameter = new JSONObject(params);
    OkHttpClient client = new OkHttpClient();

    RequestBody body = RequestBody.create(JSON, parameter.toString());
    Request request = new Request.Builder()
            .url("...")
            .post(body)
            .addHeader("content-type", "application/json; charset=utf-8")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            responsePost = response.code()+"";

        }

    });


    assertEquals(responsePost, "200");

}

}

但是当我运行测试代码时,测试失败并显示以下错误 -

org.junit.ComparisonFailure: 
Expected :
Actual   :200
<Click to see difference>

谁能帮我建议我如何编写测试代码来检查响应代码是否正确?

标签: javaandroidunit-testingpostokhttp3

解决方案


推荐阅读