iam试图编写测试用例来测试连接到Internet的功能并使用FastAndroidNetworking lib进行调用,但这给了我错误 请任何人能帮助解决这个问题
junit.framework.ComparisonFailure: 预期的:{“响应”:“这是一个获取请求”} 实际:null
@PowerMockIgnore("javax.net.ssl.*")
public class HttpServiceMethods {
private final Map<String, String> requestHeaders = new HashMap<>();
private final String expectedResponse = "{\"response\":\"This is a get request\"}";
MockWebServer server;
@Before
public void setup() throws IOException {
// instance for every unit test.
if (server == null) {
server = new MockWebServer();
}
// Schedule some responses.
MockResponse mockResponse = new MockResponse();
mockResponse.setBody(expectedResponse);
mockResponse.setResponseCode(200);
mockResponse.throttleBody(1024, 1, TimeUnit.SECONDS);
server.enqueue(mockResponse);
// Start the server.
server.start();
}
@Test
public void getRequest() throws IOException {
// reference
final AtomicReference<String> responseRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
AndroidNetworking.get(server.url("/").toString())
.addHeaders(requestHeaders)
.build()
.getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() {
@Override
public void onResponse(Response okHttpResponse, String response) {
if (okHttpResponse.isSuccessful()) {
responseRef.set(response);
latch.countDown();
}
}
@Override
public void onError(ANError anError) {
assertTrue(false);
}
});
// assertTrue(latch.await(2, SECONDS));
//Assert.assertNotNull(responseRef.get());
assertEquals(expectedResponse, responseRef.get());
}
@After
public void closeServer() throws Exception {
server.shutdown();
}
}
这是我的实际方法
public void getRequest(String requestUrl, Map<String, String> headers, CallListener callListener) {
System.out.println("Inside get.");
AndroidNetworking.get(requestUrl)
.addHeaders(headers)
.setPriority(Priority.LOW)
.build()
.getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() {
@Override
public void onResponse(Response okHttpResponse, String response) {
if (okHttpResponse != null && okHttpResponse.isSuccessful()) {
System.out.println("success");
Log.d(TAG, "Headers :" + okHttpResponse.headers());
callListener.onSuccess(response);
}
}
@Override
public void onError(ANError error) {
System.out.println("success");
if (error.getErrorCode() != 0 && error != null) {
Log.d(TAG, "onError errorCode : " + error.getErrorCode());
Log.d(TAG, "onError errorBody : " + error.getErrorBody());
Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
String fullError = error.getErrorCode() + error.getErrorBody() + error.getErrorDetail();
callListener.onFailure(fullError);
}
}
});
}