gpt4 book ai didi

java - 如何对在 AndroidViewModel 类内部进行改造调用的方法进行单元测试?

转载 作者:行者123 更新时间:2023-12-01 22:05:19 25 4
gpt4 key购买 nike

我想为通过进行改造调用来执行注册的方法编写单元测试,并且该方法位于 AndroidViewModel 类中。如何测试该方法?

public class SignUpViewModel extends AndroidViewModel {
private final Context context;
private LoadToast loadToast;

public SignUpViewModel(@NonNull Application application, Context context) {
super(application);
this.context = context;
}


public void signUpRequest(final String userName, String userPassword, String userEmail, String firstName, String lastName, String securityQuestion, String securityAnswer) {
JSONObject jsonObject = new JSONObject();
JSONObject securityJsonObject = new JSONObject();
loadToast = new LoadToast(context);
loadToast.setText("Signing in");
loadToast.show();
try {

jsonObject.put("identifier", userName);
jsonObject.put("password", userPassword);
jsonObject.put("email", userEmail);
jsonObject.put("firstName", firstName);
jsonObject.put("lastName", lastName);
securityJsonObject.put("question", securityQuestion);
securityJsonObject.put("answer", securityAnswer);
jsonObject.put("securityQuestion",securityJsonObject);

} catch (JSONException e) {
e.printStackTrace();
}

APIService apiService = RetrofitClient.getAPIService();
Call<String> signUpResponse = apiService.createUser(jsonObject.toString());
signUpResponse.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.message().equals("timeout")) {
loadToast.error();
Toast.makeText(getApplication(), "Network Connection issues please try again", Toast.LENGTH_LONG).show();
}
if (response.code() == 200) {
loadToast.success();
Toast.makeText(getApplication(), "An activation link has been sent to your email. Follow it to activate your account.", Toast.LENGTH_LONG).show();
context.startActivity(new Intent(context, LogInActivity.class));
} else if (response.code() == 409) {
loadToast.error();
Toast.makeText(getApplication(), "User With Same UserName already Exists", Toast.LENGTH_LONG).show();
} else {
loadToast.error();
Toast.makeText(getApplication(), "Something went wrong please try again", Toast.LENGTH_LONG).show();
}
}

@Override
public void onFailure(Call<String> call, Throwable t) {
loadToast.error();
Toast.makeText(getApplication(), "" + t.getMessage(), Toast.LENGTH_SHORT).show();

}
});
}


}

我的类看起来像这样,我想测试 signUpRequest 方法。我读了一些教程,但它们没有帮助。那么,我如何编写单元测试来测试我的方法?

最佳答案

根据清洁架构方法,您的 ViewModel 代码不得包含任何与框架相关的代码。尤其是上下文。您在改造中所做的所有这些工作都必须移至另一层。将此代码移动到 UseCase 或 Interactor 中并使用 Repository 模式。此链接可能会有所帮助:https://proandroiddev.com/how-to-implement-a-clean-architecture-on-android-2e5e8c8e81fe

良好的架构将使您的代码可测试。希望它会有所帮助:)

关于java - 如何对在 AndroidViewModel 类内部进行改造调用的方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58694432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com