okhttp3.mockwebserver.MockResponse Java Examples
The following examples show how to use
okhttp3.mockwebserver.MockResponse.
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 File: SpeechToTextTest.java From java-sdk with Apache License 2.0 | 7 votes |
/** * Test delete audio. * * @throws InterruptedException the interrupted exception */ @Test public void testDeleteAudio() throws InterruptedException { String id = "foo"; String audioName = "audio1"; server.enqueue( new MockResponse().addHeader(CONTENT_TYPE, HttpMediaType.APPLICATION_JSON).setBody("{}")); DeleteAudioOptions deleteOptions = new DeleteAudioOptions.Builder().customizationId(id).audioName(audioName).build(); service.deleteAudio(deleteOptions).execute(); final RecordedRequest request = server.takeRequest(); assertEquals("DELETE", request.getMethod()); assertEquals(String.format(PATH_SPECIFIC_AUDIO, id, audioName), request.getPath()); }
Example #2
Source File: MapMatchingResponseTest.java From mapbox-java with MIT License | 6 votes |
@Before public void setUp() throws Exception { server = new MockWebServer(); server.setDispatcher(new okhttp3.mockwebserver.Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { try { String response = loadJsonFixture(MAP_MATCHING_FIXTURE); return new MockResponse().setBody(response); } catch (IOException ioException) { throw new RuntimeException(ioException); } } }); server.start(); mockUrl = server.url(""); coordinates = new ArrayList<>(); coordinates.add(Point.fromLngLat(13.418946862220764, 52.50055852688439)); coordinates.add(Point.fromLngLat(13.419011235237122, 52.50113000479732)); coordinates.add(Point.fromLngLat(13.419756889343262, 52.50171780290061)); coordinates.add(Point.fromLngLat(13.419885635375975, 52.50237416816131)); coordinates.add(Point.fromLngLat(13.420631289482117, 52.50294888790448)); }
Example #3
Source File: UsersClientTest.java From blog-tutorials with MIT License | 6 votes |
@Test public void testGetUserById() throws InterruptedException { MockResponse mockResponse = new MockResponse() .addHeader("Content-Type", "application/json; charset=utf-8") .setBody("{\"id\": 1, \"name\":\"duke\"}") .throttleBody(16, 5, TimeUnit.SECONDS); mockWebServer.enqueue(mockResponse); JsonNode result = usersClient.getUserById(1L); assertEquals(1, result.get("id").asInt()); assertEquals("duke", result.get("name").asText()); RecordedRequest request = mockWebServer.takeRequest(); assertEquals("/users/1", request.getPath()); }
Example #4
Source File: FeignUnderAsyncTest.java From feign with Apache License 2.0 | 6 votes |
@Test public void decodingExceptionGetWrappedInDecode404Mode() throws Exception { server.enqueue(new MockResponse().setResponseCode(404)); thrown.expect(DecodeException.class); thrown.expectCause(isA(NoSuchElementException.class));; TestInterface api = new TestInterfaceBuilder() .decode404() .decoder(new Decoder() { @Override public Object decode(Response response, Type type) throws IOException { assertEquals(404, response.status()); throw new NoSuchElementException(); } }).target("http://localhost:" + server.getPort()); api.post(); }
Example #5
Source File: SimpleRequestTest.java From jus with Apache License 2.0 | 6 votes |
@Test public void transportProblemSync() { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); Request<String> call = example.getString().setRetryPolicy(new DefaultRetryPolicy(1,0,1)).enqueue(); try { call.getFuture().get(); fail(); } catch (Exception ignored) { // Throwable failure = ignored.getCause(); // assertThat(failure).isInstanceOf(NoConnectionError.class); // assertThat(failure.getCause()).isInstanceOf(ConnectException.class); // assertThat(failure.getCause().getMessage()).isEqualTo("Connection refused"); Response<String> response = call.getRawResponse(); assertThat(response.isSuccess()).isFalse(); assertThat(response.result).isNull(); assertThat(response.error).isNotNull(); // assertThat(response.error).isInstanceOf(NoConnectionError.class); // assertThat(response.error.getCause()).isInstanceOf(ConnectException.class); // assertThat(failure.getCause().getMessage()).isEqualTo("Connection refused"); } }
Example #6
Source File: CrudDispatcher.java From mockwebserver with Apache License 2.0 | 6 votes |
/** * Patches the specified object to the in-memory db. * * @param path * @param s * @return */ public MockResponse handlePatch(String path, String s) { MockResponse response = new MockResponse(); String body = doGet(path); if (body == null) { response.setResponseCode(404); } else { try { JsonNode patch = context.getMapper().readTree(s); JsonNode source = context.getMapper().readTree(body); JsonNode updated = JsonPatch.apply(patch, source); String updatedAsString = context.getMapper().writeValueAsString(updated); AttributeSet features = AttributeSet.merge(attributeExtractor.fromPath(path), attributeExtractor.fromResource(updatedAsString)); map.put(features, updatedAsString); response.setResponseCode(202); response.setBody(updatedAsString); } catch (Exception e) { throw new RuntimeException(e); } } return response; }
Example #7
Source File: SpeechToTextTest.java From java-sdk with Apache License 2.0 | 6 votes |
/** * Test list corpora. * * @throws InterruptedException the interrupted exception * @throws FileNotFoundException the file not found exception */ @Test public void testListCorpora() throws InterruptedException, FileNotFoundException { String id = "foo"; String corporaAsString = getStringFromInputStream( new FileInputStream("src/test/resources/speech_to_text/corpora.json")); JsonObject corpora = new JsonParser().parse(corporaAsString).getAsJsonObject(); server.enqueue( new MockResponse() .addHeader(CONTENT_TYPE, HttpMediaType.APPLICATION_JSON) .setBody(corporaAsString)); ListCorporaOptions listOptions = new ListCorporaOptions.Builder().customizationId(id).build(); Corpora result = service.listCorpora(listOptions).execute().getResult(); final RecordedRequest request = server.takeRequest(); assertEquals("GET", request.getMethod()); assertEquals(String.format(PATH_CORPORA, id), request.getPath()); assertEquals(corpora.get("corpora"), GSON.toJsonTree(result.getCorpora())); }
Example #8
Source File: AwsClientTracingTest.java From zipkin-aws with Apache License 2.0 | 6 votes |
private MockResponse getExistsResponse() { return new MockResponse().setBody("<AccessControlPolicy>\n" + " <Owner>\n" + " <ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID>\n" + " <DisplayName>[email protected]</DisplayName>\n" + " </Owner>\n" + " <AccessControlList>\n" + " <Grant>\n" + " <Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + "\t\t\txsi:type=\"CanonicalUser\">\n" + " <ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID>\n" + " <DisplayName>[email protected]</DisplayName>\n" + " </Grantee>\n" + " <Permission>FULL_CONTROL</Permission>\n" + " </Grant>\n" + " </AccessControlList>\n" + "</AccessControlPolicy> ") .setResponseCode(200) .addHeader("x-amz-request-id", "abcd"); }
Example #9
Source File: TestHttpNotificationServiceCommon.java From nifi with Apache License 2.0 | 6 votes |
@Test public void testStartNotification() throws ParserConfigurationException, SAXException, IOException, InterruptedException { mockWebServer.enqueue(new MockResponse().setResponseCode(200)); NotificationServiceManager notificationServiceManager = new NotificationServiceManager(); notificationServiceManager.setMaxNotificationAttempts(1); notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath)); notificationServiceManager.registerNotificationService(NotificationType.NIFI_STARTED, "http-notification"); notificationServiceManager.notify(NotificationType.NIFI_STARTED, "Subject", "Message"); RecordedRequest recordedRequest = mockWebServer.takeRequest(2, TimeUnit.SECONDS); assertNotNull(recordedRequest); assertEquals(NotificationType.NIFI_STARTED.name(), recordedRequest.getHeader(NOTIFICATION_TYPE_KEY)); assertEquals("Subject", recordedRequest.getHeader(NOTIFICATION_SUBJECT_KEY)); assertEquals("testing", recordedRequest.getHeader("testProp")); Buffer bodyBuffer = recordedRequest.getBody(); String bodyString =new String(bodyBuffer.readByteArray(), UTF_8); assertEquals("Message", bodyString); }
Example #10
Source File: DefaultDockerClientUnitTest.java From docker-client with Apache License 2.0 | 6 votes |
@Test(expected = NotFoundException.class) public void testUpdateConfig_NotFound() throws Exception { final DefaultDockerClient dockerClient = new DefaultDockerClient(builder); enqueueServerApiVersion("1.30"); server.enqueue(new MockResponse() .setResponseCode(404) .addHeader("Content-Type", "application/json") ); final ConfigSpec configSpec = ConfigSpec .builder() .data(Base64.encodeAsString("foobar")) .name("foo.yaml") .build(); dockerClient.updateConfig("ktnbjxoalbkvbvedmg1urrz8h", 11L, configSpec); }
Example #11
Source File: PhoneIdClientTest.java From java_telesign with MIT License | 6 votes |
public void testPhoneId() throws Exception { HashMap<String, Object> params = new HashMap<String, Object>(); this.mockServer.enqueue(new MockResponse().setBody("{}")); PhoneIdClient client = new PhoneIdClient(this.customerId, this.apiKey, this.mockServer.url("").toString().replaceAll("/$", "")); client.phoneid("18005555555", params); RecordedRequest request = this.mockServer.takeRequest(1, TimeUnit.SECONDS); assertEquals("method is not as expected", "POST", request.getMethod()); assertEquals("path is not as expected", "/v1/phoneid/18005555555", request.getPath()); assertEquals("body is not as expected", "{}", request.getBody().readUtf8()); assertEquals("Content-Type header is not as expected", "application/json", request.getHeader("Content-Type")); assertEquals("x-ts-auth-method header is not as expected", "HMAC-SHA256", request.getHeader("x-ts-auth-method")); }
Example #12
Source File: ObservableThrowingTest.java From retrocache with Apache License 2.0 | 6 votes |
@Test public void resultThrowingInOnCompletedDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!throwableRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } } }); RecordingObserver<Result<String>> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service.result().subscribe(new ForwardingObserver<Result<String>>(observer) { @Override public void onComplete() { throw e; } }); observer.assertAnyValue(); assertThat(throwableRef.get()).isSameAs(e); }
Example #13
Source File: ExonumHttpClientIntegrationTest.java From exonum-java-binding with Apache License 2.0 | 6 votes |
@Test void findServiceInfoNotFound() throws InterruptedException { // Mock response String mockResponse = "{\n" + " \"services\": [{\n" + " \"spec\": {\n" + " \"name\": \"" + SERVICE_NAME + "\",\n" + " \"id\": " + SERVICE_ID + "\n" + " },\n" + " \"status\": \"Active\"\n" + " }\n" + " ]\n" + "}"; server.enqueue(new MockResponse().setBody(mockResponse)); // Call Optional<ServiceInstanceInfo> response = exonumClient.findServiceInfo("invalid-service-name"); // Assert response assertFalse(response.isPresent()); // Assert request params RecordedRequest recordedRequest = server.takeRequest(); assertThat(recordedRequest.getMethod(), is("GET")); assertThat(recordedRequest, hasPath("api/services/supervisor/services")); }
Example #14
Source File: AbstractClientTest.java From feign with Apache License 2.0 | 6 votes |
@Test public void testAlternativeCollectionFormat() throws Exception { server.enqueue(new MockResponse().setBody("body")); TestInterface api = newBuilder() .target(TestInterface.class, "http://localhost:" + server.getPort()); Response response = api.getCSV(Arrays.asList("bar", "baz")); assertThat(response.status()).isEqualTo(200); assertThat(response.reason()).isEqualTo("OK"); // Some HTTP libraries percent-encode commas in query parameters and others don't. MockWebServerAssertions.assertThat(server.takeRequest()).hasMethod("GET") .hasOneOfPath("/?foo=bar,baz", "/?foo=bar%2Cbaz"); }
Example #15
Source File: TikXmlConverterFactoryTest.java From tikxml with Apache License 2.0 | 6 votes |
@Test public void test() throws InterruptedException, IOException, UnsupportedOperationException { server.enqueue(new MockResponse().setBody("<<?xml version=\"1.0\" encoding=\"UTF-8\"?>person><name>Hannes</name></person>")); Person person = new Person(); person.name = "outgoingName"; Call<Person> call = service.postPerson(person); Response<Person> response = call.execute(); Person responsePerson = response.body(); Assert.assertNotNull(responsePerson); Assert.assertEquals("Hannes", responsePerson.name); RecordedRequest request = server.takeRequest(); Assert.assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><person><name>outgoingName</name></person>", request.getBody().readUtf8()); Assert.assertEquals("application/xml; charset=UTF-8", request.getHeader("Content-Type")); }
Example #16
Source File: FeignTest.java From feign with Apache License 2.0 | 6 votes |
@Test public void throwsFeignExceptionIncludingBody() { server.enqueue(new MockResponse().setBody("success!")); TestInterface api = Feign.builder() .decoder((response, type) -> { throw new IOException("timeout"); }) .target(TestInterface.class, "http://localhost:" + server.getPort()); try { api.body("Request body"); } catch (FeignException e) { assertThat(e.getMessage()) .isEqualTo("timeout reading POST http://localhost:" + server.getPort() + "/"); assertThat(e.contentUTF8()).isEqualTo("Request body"); } }
Example #17
Source File: CreateUploadResourceTaskTest.java From appcenter-plugin with MIT License | 6 votes |
@Test public void should_ReturnResponse_When_RequestIsSuccessful_NonAsciiCharactersInFileName() throws Exception { // Given final UploadRequest request = baseRequest.newBuilder().setAppName("åþþ ñåmë").build(); final UploadRequest expected = request.newBuilder().setUploadId("string").setUploadUrl("string").build(); mockWebServer.enqueue(new MockResponse().setResponseCode(201).setBody("{\n" + " \"upload_id\": \"string\",\n" + " \"upload_url\": \"string\",\n" + " \"asset_id\": \"string\",\n" + " \"asset_domain\": \"string\",\n" + " \"asset_token\": \"string\"\n" + "}")); // When final UploadRequest actual = task.execute(request).get(); // Then assertThat(actual) .isEqualTo(expected); }
Example #18
Source File: ClientTest.java From tinify-java with MIT License | 6 votes |
@Test public void requestWithBadServerResponseRepeatedlyShouldThrowExceptionWithMessage() throws Exception { server.enqueue(new MockResponse() .setResponseCode(543) .setBody("<!-- this is not json -->")); server.enqueue(new MockResponse() .setResponseCode(543) .setBody("<!-- this is not json -->")); try { new Client(key).request(Client.Method.POST, "/shrink"); fail("Expected an Exception to be thrown"); } catch (Exception e) { assertEquals("Error while parsing response: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $ (HTTP 543/ParseError)", e.getMessage()); } }
Example #19
Source File: GeoApiContextTest.java From google-maps-services-java with Apache License 2.0 | 6 votes |
@Test public void testQueryParamsHaveOrderPreserved() throws Exception { // This test is important for APIs (such as the speed limits API) where multiple parameters // must be provided with the same name with order preserved. MockResponse response = new MockResponse(); response.setResponseCode(200); response.setBody("{}"); server.enqueue(response); server.start(); setMockBaseUrl(); builder .build() .get(new ApiConfig("/"), GeocodingApi.Response.class, "a", "1", "a", "2", "a", "3") .awaitIgnoreError(); server.shutdown(); RecordedRequest request = server.takeRequest(); String path = request.getPath(); assertTrue(path.contains("a=1&a=2&a=3")); }
Example #20
Source File: ClientTest.java From tinify-java with MIT License | 6 votes |
@Test public <T extends Call> void requestWithUnexpectedExceptionOnceShouldReturnResponse() throws Exception { new MockUp<T>() { int count = 1; @Mock public Response execute(Invocation inv) throws IOException { if (count == 0) { return inv.proceed(); } else { count--; throw new RuntimeException("Some exception"); } } }; server.enqueue(new MockResponse() .setResponseCode(201) .setBody("ok")); Client.Response response = new Client(key).request(Client.Method.POST, "/shrink"); assertEquals("ok", new String(response.body)); }
Example #21
Source File: SpeechToTextTest.java From java-sdk with Apache License 2.0 | 6 votes |
/** * Test delete grammar. * * @throws InterruptedException the interrupted exception */ @Test public void testDeleteGrammar() throws InterruptedException { MockResponse desiredResponse = new MockResponse().setResponseCode(200); server.enqueue(desiredResponse); String customizationId = "id"; String grammarName = "grammar_name"; DeleteGrammarOptions deleteGrammarOptions = new DeleteGrammarOptions.Builder() .customizationId(customizationId) .grammarName(grammarName) .build(); service.deleteGrammar(deleteGrammarOptions).execute(); RecordedRequest request = server.takeRequest(); assertEquals(DELETE, request.getMethod()); }
Example #22
Source File: AsyncFeignTest.java From feign with Apache License 2.0 | 6 votes |
@Test public void queryMapIterableValuesExpanded() throws Exception { server.enqueue(new MockResponse()); TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); Map<String, Object> queryMap = new LinkedHashMap<String, Object>(); queryMap.put("name", Arrays.asList("Alice", "Bob")); queryMap.put("fooKey", "fooValue"); queryMap.put("emptyListKey", new ArrayList<String>()); queryMap.put("emptyStringKey", ""); // empty values are ignored. CompletableFuture<?> cf = api.queryMap(queryMap); assertThat(server.takeRequest()) .hasPath("/?name=Alice&name=Bob&fooKey=fooValue&emptyStringKey"); checkCFCompletedSoon(cf); }
Example #23
Source File: FlowableThrowingTest.java From retrocache with Apache License 2.0 | 6 votes |
@Test public void resultThrowingInOnCompletedDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!throwableRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } } }); RecordingSubscriber<Result<String>> subscriber = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service.result().subscribe(new ForwardingSubscriber<Result<String>>(subscriber) { @Override public void onComplete() { throw e; } }); subscriber.assertAnyValue(); assertThat(throwableRef.get()).isSameAs(e); }
Example #24
Source File: GzipInterceptorTest.java From influxdb-client-java with MIT License | 6 votes |
@Nonnull private RecordedRequest newCall(@Nonnull final String path) throws IOException, InterruptedException { mockServer.enqueue(new MockResponse()); OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(interceptor) .build(); Request request = new Request.Builder() .url(url + path) .addHeader("accept", "application/json") .post(RequestBody.create(MediaType.parse("application/json"), "{name: \"Tom Type\"}")) .build(); okHttpClient.newCall(request).execute(); return mockServer.takeRequest(); }
Example #25
Source File: AuthenticateInterceptorTest.java From influxdb-client-java with MIT License | 6 votes |
@Test void authorizationSessionSignout() throws IOException, InterruptedException { mockServer.enqueue(new MockResponse()); mockServer.enqueue(new MockResponse()); InfluxDBClientOptions options = InfluxDBClientOptions.builder() .url(influxDB_URL) .authenticate("user", "secret".toCharArray()) .build(); AuthenticateInterceptor interceptor = new AuthenticateInterceptor(options); OkHttpClient okHttpClient = options.getOkHttpClient().addInterceptor(interceptor).build(); interceptor.initToken(okHttpClient); interceptor.signout(); interceptor.signout(); Assertions.assertThat(mockServer.getRequestCount()).isEqualTo(2); mockServer.takeRequest(); RecordedRequest signoutRequest = mockServer.takeRequest(); Assertions.assertThat(signoutRequest.getPath()).endsWith("/api/v2/signout"); }
Example #26
Source File: HystrixBuilderTest.java From feign with Apache License 2.0 | 6 votes |
@Test public void rxSingleList() { server.enqueue(new MockResponse().setBody("[\"foo\",\"bar\"]")); final TestInterface api = target(); final Single<List<String>> single = api.listSingle(); assertThat(single).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); final TestSubscriber<List<String>> testSubscriber = new TestSubscriber<List<String>>(); single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); assertThat(testSubscriber.getOnNextEvents().get(0)).containsExactly("foo", "bar"); }
Example #27
Source File: ITTracingRequestHandler.java From zipkin-aws with Apache License 2.0 | 6 votes |
/** Body's inherently have a structure, and we use the operation name as the span name */ @Override public void post() { String path = "table"; String body = "{\"TableName\":\"table\",\"Item\":{}}"; server.enqueue(new MockResponse()); post(client, path, body); assertThat(takeRequest().getBody().readUtf8()) .isEqualTo(body); MutableSpan span = testSpanHandler.takeRemoteSpan(Span.Kind.CLIENT); assertThat(span.remoteServiceName()) .isEqualTo("AmazonDynamoDBv2"); assertThat(span.name()) .isEqualTo("PutItem"); assertThat(testSpanHandler.takeLocalSpan().tags()) .containsEntry("aws.service_name", "AmazonDynamoDBv2") .containsEntry("aws.operation", "PutItem"); }
Example #28
Source File: CachedCallTest.java From retrocache with Apache License 2.0 | 6 votes |
@Test public void transportProblemSync() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(mServer.url("/")) .addConverterFactory(new ToStringConverterFactory()) .addCallAdapterFactory(buildSmartCacheFactory()) .build(); Service example = retrofit.create(Service.class); mServer.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); Cached<String> call = example.getString(); try { call.execute(); fail(); } catch (IOException ignored) { } }
Example #29
Source File: HystrixBuilderTest.java From feign with Apache License 2.0 | 5 votes |
@Test public void hystrixCommandList() { server.enqueue(new MockResponse().setBody("[\"foo\",\"bar\"]")); final TestInterface api = target(); final HystrixCommand<List<String>> command = api.listCommand(); assertThat(command).isNotNull(); assertThat(command.execute()).containsExactly("foo", "bar"); }
Example #30
Source File: AbstractMockWebServerTestCase.java From java-technology-stack with MIT License | 5 votes |
private MockResponse formRequest(RecordedRequest request) { assertEquals("application/x-www-form-urlencoded;charset=UTF-8", request.getHeader("Content-Type")); String body = request.getBody().readUtf8(); assertThat(body, Matchers.containsString("name+1=value+1")); assertThat(body, Matchers.containsString("name+2=value+2%2B1")); assertThat(body, Matchers.containsString("name+2=value+2%2B2")); return new MockResponse().setResponseCode(200); }