1
0
mirror of https://github.com/square/okhttp.git synced 2025-04-19 07:42:15 +03:00
okhttp/mockwebserver-junit5
renovate[bot] a51cfbf841
Update dependency com.diffplug.spotless:spotless-plugin-gradle to v7 (#8702)
* Update dependency com.diffplug.spotless:spotless-plugin-gradle to v7

* Reformat

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Jake Wharton <jw@squareup.com>
2025-03-19 15:25:20 -04:00
..
2024-01-04 00:32:07 -05:00

MockWebServer for JUnit 5

This module integrates mockwebserver3.MockWebServer with JUnit 5.

To use, first add this library as a test dependency:

testRuntimeOnly("com.squareup.okhttp3:mockwebserver3-junit5:4.12.0")

Then in tests annotated @org.junit.jupiter.api.Test, you may add a [MockWebServer] as a test method parameter. It will be shut down automatically after the test runs.

class MyTest {
  @Test
  void test(MockWebServer server) {
    ...
  }
}

Alternately you may add the [MockWebServer] as a constructor parameter:

class MyTest {
  private final MockWebServer server;

  MyTest(MockWebServer server) {
    this.server = server;
  }

  @Test
  void test() {
    ...
  }
}

Constructor injection is particularly concise in Kotlin:

class MyTest(
  private val server: MockWebServer
) {
  @Test
  fun test() {
    ...
  }
}

Multiple instances can be obtained by naming additional ones:

class MyTest(
  private val server: MockWebServer,
  @MockWebServerInstance("server2") private val server2: MockWebServer,
  @MockWebServerInstance("server3") private val server3: MockWebServer
) {
  @Test
  fun test() {
    ...
  }
}

Requirements

MockWebServer's JUnit 5 integration works on Android 7.0+ (API level 24+) and Java 8+. Note that this is above OkHttp's core requirements.