Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to mock okhttp response for JUnit test

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?

like image 367
Bryan Avatar asked Nov 07 '22 04:11

Bryan


1 Answers

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)
like image 67
Yuri Schimke Avatar answered Nov 12 '22 14:11

Yuri Schimke