gpt4 book ai didi

android - Mock Retrofit 错误 okhttp3.ResponseBody$1 无法转换

转载 作者:行者123 更新时间:2023-11-28 20:50:11 25 4
gpt4 key购买 nike

我正在尝试测试使用改造的代码 fragment ,所以我创建了一个接口(interface)来“模拟”返回,它部分工作,它可以调用入队的onresponse,但是它不能转换Response <AuthResponse> response , 遵循错误:

java.lang.ClassCastException: okhttp3.ResponseBody$1 cannot be cast to br.com.safety.safetyrecognitionsdk.data.network.auth.AuthResponse

模拟接口(interface)

public interface AuthRepositoryBoundary {

Call<AuthResponse> auth(String appKey, String projectId);

}

模拟类

public class AuthSuccessTest implements AuthRepositoryBoundary {

@Override
public Call<AuthResponse> auth(String appKey, String projectId) {

ResponseBody body = ResponseBody.create(
MediaType.parse("application/json"),
MockAuth.AUTH_SUCCESS
);

Response aResponse = Response.success(body, new okhttp3.Response.Builder() //
.code(201)
.message("OK")
.body(body)
.protocol(Protocol.HTTP_1_1)
.request(new Request.Builder().url("http://localhost/").build())
.build());

return Calls.response(aResponse);
}

}

实现

@Override
public void auth(String appKey, String projectID) {
this.authRepository.auth(appKey, projectID).enqueue(new Callback<AuthResponse>() {
@Override
public void onResponse(Call<AuthResponse> call, Response<AuthResponse> response) {
switch (response.code()) {
case 201:
authListener.onSuccess(response.body());
break;
case 401:
authListener.onUnauthorized("Unauthorized");
break;
default:
authListener.onError("Server error");
break;
}
}

@Override
public void onFailure(Call<AuthResponse> call, Throwable t) {
authListener.onError(t.getMessage());
}
});
}

测试:

@Test
public void when_success_authentication_should_be_invoke_on_success() {
this.authListenerMock = mock(AuthListener.class);
this.authRepositoryMock = mock(AuthRepositoryBoundary.class);

this.authSuccessTest = new AuthSuccessTest();

this.safetyRecognition = new SafetyRecognition()
.setCredentials("project_id", "key_id")
.auth(new Authentication(this.authListenerMock, this.authSuccessTest));

verify(this.authListenerMock).onSuccess(ArgumentMatchers.any(AuthResponse.class));
}

最佳答案

应该是

public interface AuthRepositoryBoundary {
Call<Response<AuthResponse>> auth(String appKey, String projectId);
}

然后:

public class AuthSuccessTest implements AuthRepositoryBoundary {

@Override
public Call<Response<AuthResponse>> auth(String appKey, String projectId) {

ResponseBody body = ResponseBody.create(
MediaType.parse("application/json"),
MockAuth.AUTH_SUCCESS
);

Response aResponse = Response.success(body, new okhttp3.Response.Builder() //
.code(201)
.message("OK")
.body(body)
.protocol(Protocol.HTTP_1_1)
.request(new Request.Builder().url("http://localhost/").build())
.build());

return Calls.response(aResponse);
}}

?

关于android - Mock Retrofit 错误 okhttp3.ResponseBody$1 无法转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50103135/

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