5

I'm making an outbound HTTP request to a 3rd party API via okhttp:

public @Nullable result Call3rdParty {
    OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
        .readTimeout(RW_TIMEOUT, TimeUnit.MILLISECONDS)
        .retryOnConnectionFailure(true)
        .build();
    

    Request request = new Request.Builder()
       .url(url)
       .build();
    Response response = client.newCall(request).execute();

    //Deserialize and do minor data manipulation...
}

I want to create a unit test and mock the responses.

  private MockWebServer server;

  @Before
  public void setUp() throws IOException {
    this.server = new MockWebServer();
    this.server.start();
  }

  @After
  public void tearDown() throws IOException {
    this.server.shutdown();
  }

  @Test
  public void Test_SUCCESS() throws Exception {
    String json = readFileAsString(file);
    this.server.enqueue(new MockResponse().setResponseCode(200).setBody(json));
    //TODO: What to do here??
   }

After a mock response has been enqueued, what do I need to do return a mock response and use it in the remaining part of the method I'm testing?

Bryan
  • 105
  • 1
  • 8
  • The code in the question isn't complete and is answered by hundreds of online tutorials etc. – Yuri Schimke Oct 01 '20 at 06:50
  • @YuriSchimke please mention one of them here for reference. – Asad Shakeel Jun 06 '21 at 07:13
  • A random one, it's hard to know what the best one is given there are a lot of different ways to implement or goals of this testing https://medium.com/android-news/unit-test-api-calls-with-mockwebserver-d4fab11de847 – Yuri Schimke Jun 06 '21 at 23:57

1 Answers1

1

The project documentation covers this

https://github.com/square/okhttp/tree/master/mockwebserver

  // Ask the server for its URL. You'll need this to make HTTP requests.
  HttpUrl url = server.url("/myendpoint");

  // Call your client code here, passing the server location to it
  response = Call3rdParty(url)
Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69