我已经在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>
任何人都可以帮我建议如何编写测试代码来检查响应代码是否正确吗?