3

I try to use MockWebServer to the various responses to my API. I have made a simple example just to try that what I would like to do is a working method.

Isn't the mockWebServer meant to 'mock' the endpoint of my http connections? Like a real server? Whenever I try to make a call I got UnknownHostException.

Am I using it wrong? Isn't it supposed to just replace a server's response? (mock it)

E D I T:

I have internet permission in manifest.

I use:

 androidTestImplementation 'com.squareup.okhttp3:mockwebserver:3.9.1'

Code:

 @Test
    public void myTest() throws IOException, InterruptedException {

        String url = "http://some-mock-url.com";

        MockWebServer server = new MockWebServer();
        server.enqueue(new MockResponse().setBody("Something not valid JSON response"));
        server.start();

        server.url(url);

        final CountDownLatch signal = new CountDownLatch(1);

        AndroidNetworking.get(url)
                .addQueryParameter("some_key", "some_value12345")
                .addHeaders("token", "token_1231234")
                .build()
                .getAsJSONObject(new JSONObjectRequestListener() {

                                     @Override
                                     public void onResponse(JSONObject response) {
                                         signal.countDown();
                                         Log.i("Response", "jsonObject: " + response);
                                     }

                                     @Override
                                     public void onError(ANError anError) {
                                         signal.countDown();
                                         Log.i("Response", "error: " + anError.getMessage());
                                     }
                                 }
                );
        signal.await();
    }

Logcat:

com.androidnetworking.error.ANError: java.net.UnknownHostException: Unable to resolve host "some-mock-url.com": No address associated with hostname

Adam Varhegyi
  • 11,307
  • 33
  • 124
  • 222

3 Answers3

1

I have found an example when the order is reversed.

So instead of setting an URL to the Mock server, you have to set the Mock server's url to the actual URL, so like:

myAPIsURL= mockWebServer.url("/").toString();

And not

mockWebServer.url(myAPIsURL);

Adam Varhegyi
  • 11,307
  • 33
  • 124
  • 222
0

In case someone has the same problem, MockWebServer is from the same dependency of OKHttp so they both need to have the same dependency version.

htafoya
  • 18,261
  • 11
  • 80
  • 104
-1

It was a proxy issue for me . i followed this solution. I am not getting the unknown host exception now. https://stackoverflow.com/a/41714851/5856146

Kaveri
  • 151
  • 1
  • 6