Java Code Examples for okhttp3.mockwebserver.MockWebServer

The following examples show how to use okhttp3.mockwebserver.MockWebServer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: mapbox-java   Source File: MapboxOptimizationTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  server = new MockWebServer();

  server.setDispatcher(new okhttp3.mockwebserver.Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {

      String resource = OPTIMIZATION_FIXTURE;

      try {
        String body = loadJsonFixture(resource);
        return new MockResponse().setBody(body);
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
    }
  });
  server.start();
  mockUrl = server.url("");
}
 
Example 2
Source Project: java-stellar-sdk   Source File: ServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckMemoRequiredWithMemo() throws IOException, AccountRequiresMemoException {
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.setDispatcher(buildTestCheckMemoRequiredMockDispatcher());
    mockWebServer.start();
    HttpUrl baseUrl = mockWebServer.url("");
    Server server = new Server(baseUrl.toString());

    KeyPair source = KeyPair.fromSecretSeed("SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY");
    Account account = new Account(source.getAccountId(), 1L);
    Transaction transaction = new Transaction.Builder(account, Network.PUBLIC)
            .addOperation(new PaymentOperation.Builder(DESTINATION_ACCOUNT_MEMO_REQUIRED_A, new AssetTypeNative(), "10").build())
            .addOperation(new PathPaymentStrictReceiveOperation.Builder(new AssetTypeNative(), "10", DESTINATION_ACCOUNT_MEMO_REQUIRED_B, new AssetTypeCreditAlphaNum4("BTC", "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2"), "5").build())
            .addOperation(new PathPaymentStrictSendOperation.Builder(new AssetTypeNative(), "10", DESTINATION_ACCOUNT_MEMO_REQUIRED_C, new AssetTypeCreditAlphaNum4("BTC", "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2"), "5").build())
            .addOperation(new AccountMergeOperation.Builder(DESTINATION_ACCOUNT_MEMO_REQUIRED_D).build())
            .setTimeout(Transaction.Builder.TIMEOUT_INFINITE)
            .addMemo(new MemoText("Hello, Stellar."))
            .setBaseFee(100)
            .build();
    transaction.sign(source);
    server.submitTransaction(transaction);
    server.submitTransaction(feeBump(transaction));
}
 
Example 3
Source Project: appcenter-plugin   Source File: MockWebServerUtil.java    License: MIT License 6 votes vote down vote up
private static void enqueueSuccess(final @Nonnull MockWebServer mockAppCenterServer, final @Nonnull MockWebServer mockUploadServer) {
    mockAppCenterServer.enqueue(new MockResponse().setResponseCode(HTTP_CREATED).setBody("{\n" +
        "  \"upload_id\": \"string\",\n" +
        "  \"upload_url\": \"" + mockUploadServer.url("/").toString() + "\",\n" +
        "  \"asset_id\": \"string\",\n" +
        "  \"asset_domain\": \"string\",\n" +
        "  \"asset_token\": \"string\"\n" +
        "}"));
    mockUploadServer.enqueue(new MockResponse().setResponseCode(HTTP_OK));
    mockAppCenterServer.enqueue(new MockResponse().setResponseCode(HTTP_OK).setBody("{\n" +
        "  \"release_id\": 0,\n" +
        "  \"release_url\": \"string\"\n" +
        "}"));
    mockAppCenterServer.enqueue(new MockResponse().setResponseCode(HTTP_OK).setBody("{\n" +
        "  \"release_notes\": \"string\"\n" +
        "}"));
}
 
Example 4
Source Project: tinify-java   Source File: TinifyTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setup() throws IOException {
    Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);

    server = new MockWebServer();
    server.start();
    new MockUp<HttpUrl>()
    {
        @Mock
        @SuppressWarnings("unused")
        HttpUrl parse(Invocation inv, String url)
        {
            if (url.contains("localhost")) {
                return inv.proceed();
            } else {
                return new HttpUrl.Builder()
                        .scheme("http")
                        .host(server.getHostName())
                        .port(server.getPort())
                        .encodedPath(url.replaceFirst(Client.API_ENDPOINT, ""))
                        .build();
            }
        }
    };
}
 
Example 5
@Test
public void getReturnsPushGatewayProvider() throws Exception {
    final MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_ACCEPTED));
    server.start();

    final MetricsPrometheusReporterConfiguration configuration = new MetricsPrometheusReporterConfiguration() {
        @Override
        public HostAndPort getAddress() {
            return HostAndPort.fromParts(server.getHostName(), server.getPort());
        }
    };
    final PushGatewayProvider provider = new PushGatewayProvider(configuration);
    final PushGateway pushGateway = provider.get();
    pushGateway.push(CollectorRegistry.defaultRegistry, "test");

    final RecordedRequest request = server.takeRequest();
    assertEquals("PUT", request.getMethod());
    assertEquals("/metrics/job/test", request.getPath());
    assertEquals("text/plain; version=0.0.4; charset=utf-8", request.getHeader("Content-Type"));
    assertEquals(0L, request.getBodySize());
}
 
Example 6
Source Project: snowplow-android-tracker   Source File: EmitterTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testEmitTwoGetEvents() throws InterruptedException, IOException {
    MockWebServer mockServer = getMockServer();
    EmittableEvents emittableEvents = getEmittableEvents(mockServer, 2);
    Emitter emitter = getEmitter(getMockServerURI(mockServer), HttpMethod.GET, BufferOption.Single, RequestSecurity.HTTP);

    LinkedList<RequestResult> result = emitter.performAsyncEmit(emitter.buildRequests(emittableEvents));
    assertEquals(2, result.size());
    assertEquals(0, result.getFirst().getEventIds().getFirst().intValue());
    assertEquals(1, result.get(1).getEventIds().getFirst().intValue());

    RecordedRequest req = mockServer.takeRequest(2, TimeUnit.SECONDS);
    assertGETRequest(req);

    req = mockServer.takeRequest(2, TimeUnit.SECONDS);
    assertGETRequest(req);

    mockServer.shutdown();
}
 
Example 7
Source Project: focus-android   Source File: WebViewDataTest.java    License: Mozilla Public License 2.0 6 votes vote down vote up
private void assertPathsHaveBeenRequested(MockWebServer webServer, String... paths) throws InterruptedException {
    final List<String> expectedPaths = new ArrayList<>(paths.length);
    Collections.addAll(expectedPaths, paths);

    RecordedRequest request;

    while ((request = webServer.takeRequest(waitingTime, TimeUnit.MILLISECONDS)) != null) {
        if (!expectedPaths.remove(request.getPath())) {
            throw new AssertionError("Unknown path requested: " + request.getPath());
        }
    }

    if (!expectedPaths.isEmpty()) {
        throw new AssertionError("Expected paths not requested: " + expectedPaths);
    }
}
 
Example 8
Source Project: JavaSteam   Source File: WebAPITest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    lock = new CountDownLatch(1);
    server = new MockWebServer();

    server.enqueue(new MockResponse().setBody("" +
            "\"root\"" +
            "{" +
            "    \"name\" \"stringvalue\"" +
            "}"));

    server.start();

    baseUrl = server.url("/");

    config = SteamConfiguration.create(new Consumer<ISteamConfigurationBuilder>() {
        @Override
        public void accept(ISteamConfigurationBuilder b) {
            b.withWebAPIBaseAddress(baseUrl.toString());
        }
    });
}
 
Example 9
Source Project: java-cloudant   Source File: IndexTests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Uses a mock web server to record a _find request using the specified options
 *
 * @param builder query to make
 * @return the JsonElement from the use_index property of the JsonObject POSTed with the request
 * @throws Exception
 */
private JsonElement getUseIndexFromRequest(QueryBuilder builder) throws Exception {
    JsonElement useIndexRequestProperty = null;
    MockWebServer mockWebServer = new MockWebServer();
    // Return 200 OK with empty array of docs (once for each request)
    mockWebServer.enqueue(new MockResponse().setBody("{ \"docs\" : []}"));
    mockWebServer.start();
    try {
        CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder
                (mockWebServer).build();
        Database db = client.database("mock", false);
        db.query(builder.build(), Movie.class);
        RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
        JsonObject body = new Gson().fromJson(request.getBody().readUtf8(), JsonObject.class);
        useIndexRequestProperty = body.get("use_index");
    } finally {
        mockWebServer.shutdown();
    }
    return useIndexRequestProperty;
}
 
Example 10
Source Project: tinify-java   Source File: ClientTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setup() throws IOException {
    Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);

    server = new MockWebServer();
    server.start();
    subject = new Client(key);
    new MockUp<HttpUrl>()
    {
        @Mock
        @SuppressWarnings("unused")
        HttpUrl parse(Invocation inv, String url)
        {
            if (url.contains("localhost")) {
                return inv.proceed();
            } else {
                return new HttpUrl.Builder()
                        .scheme("http")
                        .host(server.getHostName())
                        .port(server.getPort())
                        .encodedPath("/shrink")
                        .build();
            }
        }
    };
}
 
Example 11
@Before
public void setUpWebServer() throws IOException {
    webServer = new MockWebServer();

    // Test page
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("image_test.html")));
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("rabbit.jpg")));
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("download.jpg")));
    // Download
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("image_test.html")));
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("rabbit.jpg")));
    webServer.enqueue(new MockResponse()
            .setBody(TestHelper.readTestAsset("download.jpg")));
}
 
Example 12
Source Project: sixpack-java   Source File: SixpackTest.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testGetClientIdInterceptor() throws IOException {
    String clientId = "test-client-id";

    MockWebServer webServer = new MockWebServer();
    webServer.enqueue(new MockResponse());
    webServer.start();
    HttpUrl url = webServer.url("/");

    Interceptor clientIdInterceptor = Sixpack.getClientIdInterceptor(clientId);
    assertNotNull(clientIdInterceptor);

    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(clientIdInterceptor)
            .build();

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

    assertEquals(clientId, response.request().url().queryParameter("client_id"));
}
 
Example 13
Source Project: focus-android   Source File: CustomTabTest.java    License: Mozilla Public License 2.0 6 votes vote down vote up
private void startWebServer() {
    final Context appContext = InstrumentationRegistry.getInstrumentation()
            .getTargetContext()
            .getApplicationContext();

    PreferenceManager.getDefaultSharedPreferences(appContext)
            .edit()
            .putBoolean(FIRSTRUN_PREF, true)
            .apply();

    webServer = new MockWebServer();

    try {
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("plain_test.html")));
        webServer.start();
    } catch (IOException e) {
        throw new AssertionError("Could not start web server", e);
    }
}
 
Example 14
Source Project: mapbox-java   Source File: IsochroneTestUtils.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    server = new MockWebServer();
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            try {
                String response = loadJsonFixture(ISOCHRONE_WITH_POLYGONS_VALID);
                if (request.getPath().contains("polygons=false")) {
                    response = loadJsonFixture(ISOCHRONE_NO_POLYGONS_VALID);
                }
                return new MockResponse().setBody(response);
            } catch (IOException ioException) {
                throw new RuntimeException(ioException);
            }
        }
    });
    server.start();
    mockUrl = server.url("");
}
 
Example 15
Source Project: mapbox-java   Source File: TilequeryTestUtils.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    server = new MockWebServer();
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            try {
                String response = loadJsonFixture(TILEQUERY_VALID);
                if (request.getPath().contains("limit")) {
                    response = loadJsonFixture(TILEQUERY_ALL_PARAM_VALID);
                }
                return new MockResponse().setBody(response);
            } catch (IOException ioException) {
                throw new RuntimeException(ioException);
            }
        }
    });
    server.start();
    mockUrl = server.url("");
}
 
Example 16
Source Project: auth0-java   Source File: TelemetryInterceptorTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldNotAddTelemetryHeaderIfDisabled() throws Exception {
    TelemetryInterceptor interceptor = new TelemetryInterceptor(telemetry);
    interceptor.setEnabled(false);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build();

    MockWebServer server = new MockWebServer();
    server.start();
    server.enqueue(new MockResponse());

    Request request = new Request.Builder()
            .get()
            .url(server.url("/"))
            .build();
    client.newCall(request).execute();

    RecordedRequest finalRequest = server.takeRequest();
    assertThat(finalRequest.getHeader("Auth0-Client"), is(nullValue()));

    server.shutdown();
}
 
Example 17
Source Project: java-stellar-sdk   Source File: FederationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveSuccess() throws IOException {
  MockWebServer mockWebServer = new MockWebServer();
  mockWebServer.start();

  HttpUrl baseUrl = mockWebServer.url("");
  String domain = String.format("%s:%d", baseUrl.host(), baseUrl.port());

    String stellarToml =
            "FEDERATION_SERVER = \"http://"+domain+"/federation\"";
    String successResponse =
            "{\"stellar_address\":\"bob*"+domain+"\",\"account_id\":\"GCW667JUHCOP5Y7KY6KGDHNPHFM4CS3FCBQ7QWDUALXTX3PGXLSOEALY\"}";

  mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(stellarToml));
  mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(successResponse));

  FederationResponse response = Federation.resolve("bob*"+domain);
  assertEquals(response.getStellarAddress(), "bob*"+domain);
  assertEquals(response.getAccountId(), "GCW667JUHCOP5Y7KY6KGDHNPHFM4CS3FCBQ7QWDUALXTX3PGXLSOEALY");
  assertNull(response.getMemoType());
  assertNull(response.getMemo());
}
 
Example 18
Source Project: snowplow-android-tracker   Source File: TrackerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testTrackWithSession() throws Exception {
    MockWebServer mockWebServer = getMockServer(1);

    Emitter emitter = new Emitter.EmitterBuilder(getMockServerURI(mockWebServer), getContext())
            .option(BufferOption.Single)
            .build();
    emitter.waitForEventStore();

    Tracker tracker = new Tracker.TrackerBuilder(emitter, "myNamespace", "myAppId", getContext())
        .base64(false)
        .level(LogLevel.VERBOSE)
        .sessionContext(true)
        .mobileContext(false)
        .geoLocationContext(false)
        .foregroundTimeout(5)
        .backgroundTimeout(5)
        .sessionCheckInterval(1)
        .timeUnit(TimeUnit.SECONDS)
        .build();

    assertNotNull(tracker.getSession());
    tracker.resumeSessionChecking();
    Thread.sleep(2000);
    tracker.pauseSessionChecking();

    mockWebServer.shutdown();
}
 
Example 19
Source Project: snowplow-android-tracker   Source File: EmitterTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testEmitMixedEvents() throws InterruptedException, IOException, JSONException {
    Executor.setThreadCount(10);
    Executor.shutdown();

    MockWebServer mockServer = getMockServer();
    getEmittableEvents(mockServer, 5);
    getBadEmittableEvents(mockServer, 5);

    new EventStore(getContext(), 5).removeAllEvents();
    Emitter emitter = new Emitter.EmitterBuilder(getMockServerURI(mockServer), getContext())
            .option(BufferOption.Single)
            .method(HttpMethod.GET)
            .tick(1)
            .callback(getCallback())
            .emptyLimit(5)
            .sendLimit(10)
            .build();

    TrackerPayload payload = new TrackerPayload();
    payload.add("key", "value");
    payload.add("e", "pv");

    for (int i = 0; i < 10; i++) {
        emitter.add(payload);
    }
    Thread.sleep(1000);

    for (int i = 0; i < 10; i++) {
        mockServer.takeRequest(20, TimeUnit.SECONDS);
    }

    emitter.getEventStore().removeAllEvents();
    emitter.shutdown();

    mockServer.shutdown();
}
 
Example 20
Source Project: presto   Source File: TestQueryRunner.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setup()
        throws IOException
{
    server = new MockWebServer();
    server.start();
}
 
Example 21
@Before
public void beforeEachTest() throws IOException {
    mockWebServer = new MockWebServer();
    mockWebServer.start();
    okApiService = applicationComponent.okApiService();

    HostSelectionInterceptor interceptor = applicationComponent.hostInteceptor();
    interceptor.setHost(mockWebServer.url("").toString());
}
 
Example 22
@Before
public void setUp() {

	this.factory = new ReactorResourceFactory();
	this.factory.afterPropertiesSet();

	this.server = new MockWebServer();
	this.webClient = WebClient
			.builder()
			.clientConnector(initConnector())
			.baseUrl(this.server.url("/").toString())
			.build();
}
 
Example 23
@Before
public void setUp() throws Exception {
	this.server = new MockWebServer();
	this.server.setDispatcher(new TestDispatcher());
	this.server.start();
	this.port = this.server.getPort();
	this.baseUrl = "http://localhost:" + this.port;
}
 
Example 24
Source Project: snowplow-android-tracker   Source File: EmitterTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testEmitOnlySuccessEvents() throws InterruptedException, IOException, JSONException {
    Executor.setThreadCount(10);
    Executor.shutdown();

    MockWebServer mockServer = getMockServer();
    getEmittableEvents(mockServer, 10);

    new EventStore(getContext(), 5).removeAllEvents();
    Emitter emitter = new Emitter.EmitterBuilder(getMockServerURI(mockServer), getContext())
            .option(BufferOption.Single)
            .method(HttpMethod.GET)
            .tick(1)
            .callback(getCallback())
            .emptyLimit(5)
            .sendLimit(10)
            .build();

    TrackerPayload payload = new TrackerPayload();
    payload.add("key", "value");
    payload.add("e", "pv");

    for (int i = 0; i < 10; i++) {
        emitter.add(payload);
    }
    Thread.sleep(1000);

    for (int i = 0; i < 10; i++) {
        mockServer.takeRequest(20, TimeUnit.SECONDS);
    }

    emitter.getEventStore().removeAllEvents();
    emitter.shutdown();

    mockServer.shutdown();
}
 
Example 25
Source Project: stetho   Source File: StethoInterceptorTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testWithRequestCompression() throws IOException {
  AtomicReference<NetworkEventReporter.InspectorRequest> capturedRequest =
      hookAlmostRealRequestWillBeSent(mMockEventReporter);

  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse()
      .setBody("Success!"));

  final byte[] decompressed = "Request text".getBytes();
  final byte[] compressed = compress(decompressed);
  assertNotEquals(
      "Bogus test: decompressed and compressed lengths match",
      compressed.length, decompressed.length);

  RequestBody compressedBody = RequestBody.create(
      MediaType.parse("text/plain"),
      compress(decompressed));
  Request request = new Request.Builder()
      .url(server.url("/"))
      .addHeader("Content-Encoding", "gzip")
      .post(compressedBody)
      .build();
  Response response = mClientWithInterceptor.newCall(request).execute();

  // Force a read to complete the flow.
  response.body().string();

  assertArrayEquals(decompressed, capturedRequest.get().body());
  Mockito.verify(mMockEventReporter)
      .dataSent(
          anyString(),
          eq(decompressed.length),
          eq(compressed.length));

  server.shutdown();
}
 
Example 26
Source Project: snowplow-android-tracker   Source File: EventSendingTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressLint("DefaultLocale")
public String getMockServerURI(MockWebServer mockServer) {
    if (mockServer != null) {
        return String.format("%s:%d", mockServer.getHostName(), mockServer.getPort());
    }
    return null;
}
 
Example 27
Source Project: java-stellar-sdk   Source File: ServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNextPage() throws IOException, URISyntaxException {
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(operationsPageResponse));
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(operationsPageResponse));
    mockWebServer.start();
    HttpUrl baseUrl = mockWebServer.url("");
    Server server = new Server(baseUrl.toString());

    Page<OperationResponse> page = server.operations().execute();
    assertEquals(1, page.getRecords().size());
    assertEquals("dd9d10c80a344f4464df3ecaa63705a5ef4a0533ff2f2099d5ef371ab5e1c046", page.getRecords().get(0).getTransactionHash());
    Page<OperationResponse> nextPage = page.getNextPage(server.getHttpClient());
    assertEquals(1, page.getRecords().size());
}
 
Example 28
Source Project: mapbox-java   Source File: OptimizationWaypointTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  final String json = loadJsonFixture(OPTIMIZATION_FIXTURE);
  object = new JsonParser().parse(json).getAsJsonObject();

  server = new MockWebServer();
  server.setDispatcher(new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      return new MockResponse().setBody(json);
    }
  });
  server.start();
  mockUrl = server.url("");
}
 
Example 29
Source Project: snowplow-android-tracker   Source File: EventSendingTest.java    License: Apache License 2.0 5 votes vote down vote up
public LinkedList<RecordedRequest> getRequests(MockWebServer mockServer, int count) throws Exception {
    LinkedList<RecordedRequest> requests = new LinkedList<>();
    for (int i = 0; i < count; i++) {
        requests.add(mockServer.takeRequest());
    }
    return requests;
}
 
Example 30
Source Project: influxdb-client-java   Source File: AbstractMockServerTest.java    License: MIT License 5 votes vote down vote up
/**
 * Start Mock server.
 *
 * @return the mock server URL
 */
@Nonnull
protected String startMockServer() {

    mockServer = new MockWebServer();
    try {
        mockServer.start();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return mockServer.url("/").url().toString();
}