Java Code Examples for okhttp3.mockwebserver.MockResponse#setBody()
The following examples show how to use
okhttp3.mockwebserver.MockResponse#setBody() .
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: GeoApiContextTest.java From google-maps-services-java with Apache License 2.0 | 6 votes |
@Test(expected = IOException.class) public void testRetryCanBeDisabled() throws Exception { // Set up 2 mock responses, an error that shouldn't be retried and a success MockResponse errorResponse = new MockResponse(); errorResponse.setStatus("HTTP/1.1 500 Internal server error"); errorResponse.setBody("Uh-oh. Server Error."); server.enqueue(errorResponse); MockResponse goodResponse = new MockResponse(); goodResponse.setResponseCode(200); goodResponse.setBody("{\n \"results\" : [],\n \"status\" : \"ZERO_RESULTS\"\n}"); server.enqueue(goodResponse); server.start(); setMockBaseUrl(); // This should disable the retry, ensuring that the success response is NOT returned builder.disableRetries(); // We should get the error response here, not the success response. builder.build().get(new ApiConfig("/"), GeocodingApi.Response.class, "k", "v").await(); }
Example 2
Source File: PrebidServerAdapterTest.java From prebid-mobile-android with Apache License 2.0 | 6 votes |
@Test public void testStopRequest() throws Exception { MockResponse response = new MockResponse(); response.setBody(MockPrebidServerResponses.noBid()); response.setBodyDelay(1, TimeUnit.SECONDS); server.enqueue(response); HttpUrl hostUrl = server.url("/"); Host.CUSTOM.setHostUrl(hostUrl.toString()); PrebidMobile.setPrebidServerHost(Host.CUSTOM); PrebidMobile.setPrebidServerAccountId("12345"); PrebidMobile.setShareGeoLocation(true); PrebidMobile.setApplicationContext(activity.getApplicationContext()); final DemandAdapter.DemandAdapterListener mockListener = mock(DemandAdapter.DemandAdapterListener.class); final PrebidServerAdapter adapter = new PrebidServerAdapter(); HashSet<AdSize> sizes = new HashSet<>(); sizes.add(new AdSize(320, 50)); final RequestParams requestParams = new RequestParams("67890", AdType.BANNER, sizes); final String uuid = UUID.randomUUID().toString(); adapter.requestDemand(requestParams, mockListener, uuid); bgScheduler.runOneTask(); adapter.stopRequest(uuid); Robolectric.flushBackgroundThreadScheduler(); Robolectric.flushForegroundThreadScheduler(); verify(mockListener, never()).onDemandFailed(ResultCode.NO_BIDS, uuid); }
Example 3
Source File: GeoApiContextTest.java From google-maps-services-java with Apache License 2.0 | 6 votes |
@Test public void testRetryEventuallyReturnsTheRightException() throws Exception { MockResponse errorResponse = new MockResponse(); errorResponse.setStatus("HTTP/1.1 500 Internal server error"); errorResponse.setBody("Uh-oh. Server Error."); // Enqueue some error responses. for (int i = 0; i < 10; i++) { server.enqueue(errorResponse); } server.start(); // Wire the mock web server to the context setMockBaseUrl(); builder.retryTimeout(5, TimeUnit.SECONDS); try { builder.build().get(new ApiConfig("/"), GeocodingApi.Response.class, "k", "v").await(); } catch (IOException ioe) { // Ensure the message matches the status line in the mock responses. assertEquals("Server Error: 500 Internal server error", ioe.getMessage()); return; } fail("Internal server error was expected but not observed."); }
Example 4
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 5
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 6
Source File: InfluxDBInterpeterTest.java From zeppelin with Apache License 2.0 | 6 votes |
@Nonnull protected MockResponse createResponse(final String data, final String contentType, final boolean chunked) { MockResponse response = new MockResponse() .setHeader("Content-Type", contentType + "; charset=utf-8") .setHeader("Date", "Tue, 26 Jun 2018 13:15:01 GMT"); if (chunked) { response.setChunkedBody(data, data.length()); } else { response.setBody(data); } return response; }
Example 7
Source File: Fixture.java From mockwebserverplus with Apache License 2.0 | 6 votes |
public MockResponse toMockResponse() { MockResponse mockResponse = new MockResponse(); if (this.statusCode != 0) { mockResponse.setResponseCode(this.statusCode); } if (this.body != null) { mockResponse.setBody(this.body); } if (this.delay != 0) { mockResponse.setBodyDelay(this.delay, TimeUnit.MILLISECONDS); } if (this.headers != null) { for (String header : this.headers) { mockResponse.addHeader(header); } } return mockResponse; }
Example 8
Source File: ZooniverseClientTest.java From android-galaxyzoo with GNU General Public License v3.0 | 5 votes |
@Test public void testLoginWithFailure() throws IOException { final MockWebServer server = new MockWebServer(); //On failure, the server's response code is HTTP_OK, //but it has a "success: false" parameter. final MockResponse response = new MockResponse(); response.setResponseCode(HttpURLConnection.HTTP_OK); response.setBody("test nonsense failure message"); server.enqueue(response); server.start(); final ZooniverseClient client = createZooniverseClient(server); try { final LoginUtils.LoginResult result = client.loginSync("testusername", "testpassword"); assertNotNull(result); assertFalse(result.getSuccess()); } catch (final ZooniverseClient.LoginException e) { assertTrue(e.getCause() instanceof MalformedJsonException); } server.shutdown(); }
Example 9
Source File: ZooniverseClientTest.java From android-galaxyzoo with GNU General Public License v3.0 | 5 votes |
@Test public void testUploadWithFailure() throws IOException { final MockWebServer server = new MockWebServer(); final MockResponse response = new MockResponse(); response.setResponseCode(HttpURLConnection.HTTP_UNAUTHORIZED); response.setBody("test nonsense failure message"); server.enqueue(response); server.start(); final ZooniverseClient client = createZooniverseClient(server); final List<HttpUtils.NameValuePair> values = new ArrayList<>(); values.add(new HttpUtils.NameValuePair("test nonsense", "12345")); try { final boolean result = client.uploadClassificationSync("testAuthName", "testAuthApiKey", TEST_GROUP_ID, values); assertFalse(result); } catch (final ZooniverseClient.UploadException e) { //This is (at least with okhttp.mockwebserver) a normal //event if the upload was refused via an error response code. assertTrue(e.getCause() instanceof IOException); } server.shutdown(); }
Example 10
Source File: LocalTestServerContext.java From google-maps-services-java with Apache License 2.0 | 5 votes |
LocalTestServerContext(String responseBody) throws IOException { this.server = new MockWebServer(); MockResponse response = new MockResponse(); response.setHeader("Content-Type", "application/json"); response.setBody(responseBody); server.enqueue(response); server.start(); this.context = new GeoApiContext.Builder() .apiKey("AIzaFakeKey") .baseUrlOverride("http://127.0.0.1:" + server.getPort()) .build(); }
Example 11
Source File: TestActivityRepoList.java From AndroidStarter with Apache License 2.0 | 5 votes |
@Frutilla( Given = "A single GitHub repo from the API", When = "", Then = "It should display a repo named \"git-consortium\"" ) @Test public void test_ListRepos_WithOneRepo_DisplayListWithOnlyThisRepo() { Given: { final String lsOneRepoJSONData = mLocalifyClient.localify().loadRawFile(fr.guddy.androidstarter.test.R.raw.repos_octocat); final MockResponse loMockResponseWithOneRepo = new MockResponse().setResponseCode(200); loMockResponseWithOneRepo.setBody(lsOneRepoJSONData); mMockWebServer.enqueue(loMockResponseWithOneRepo); try { mMockWebServer.start(4000); } catch (@NonNull final Exception loException) { loException.printStackTrace(); } mActivity = mActivityTestRule.launchActivity(null); } When: { } Then: { final boolean lbFoundTheRepo = mSolo.waitForText("git-consortium", 1, 5000L, true); assertThat(lbFoundTheRepo).isTrue(); } }
Example 12
Source File: ClientTest.java From Drinks with Apache License 2.0 | 5 votes |
private void enqueueServerResponse(String bodyFile) throws IOException { MockResponse serverResponse = new MockResponse(); Buffer buffer = new Buffer(); buffer.readFrom(getClass().getResourceAsStream(bodyFile)); serverResponse.setBody(buffer); server.enqueue(serverResponse); }
Example 13
Source File: MatchableCallsRequestDispatcher.java From RESTMock with Apache License 2.0 | 5 votes |
private MockResponse createNotMockedResponse(String httpMethod) { MockResponse mockResponse = new MockResponse().setResponseCode(500); if (!httpMethod.equals("HEAD")) { mockResponse.setBody(RESTMockServer.RESPONSE_NOT_MOCKED); } return mockResponse; }
Example 14
Source File: Dhis2MockServer.java From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License | 5 votes |
@NonNull private MockResponse createMockResponse(String fileName) { try { String body = fileReader.getStringFromFile(fileName); MockResponse response = new MockResponse(); response.setResponseCode(OK_CODE); response.setBody(body); return response; } catch (IOException e) { return new MockResponse().setResponseCode(500).setBody("Error reading JSON file for MockServer"); } }
Example 15
Source File: LocalResponseDispatcher.java From mockstar with MIT License | 5 votes |
@Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { MockResponse mockResponse = new MockResponse(); String scenario = getScenario(request); if (scenario != null) { try { mockResponse.setBody(readFile(scenario)); mockResponse.setResponseCode(200); } catch (IOException e) { e.printStackTrace(); } } return mockResponse; }
Example 16
Source File: MockWebServerTest.java From mapbox-events-android with MIT License | 5 votes |
void enqueueMockResponse(int code, String fileName) throws IOException { mockResponse = new MockResponse(); mockResponse.setResponseCode(code); String fileContent = obtainContentFromFile(fileName); mockResponse.setBody(fileContent); server.enqueue(mockResponse); }
Example 17
Source File: AwsClientTracingTest.java From zipkin-aws with Apache License 2.0 | 4 votes |
private MockResponse createDeleteItemResponse() { MockResponse response = new MockResponse(); response.setBody("{}"); response.addHeader("x-amzn-RequestId", "abcd"); return response; }
Example 18
Source File: ZooniverseClientTest.java From android-galaxyzoo with GNU General Public License v3.0 | 4 votes |
@Test public void testUploadWithSuccess() throws IOException, InterruptedException, ZooniverseClient.UploadException { final MockWebServer server = new MockWebServer(); final MockResponse response = new MockResponse(); response.setResponseCode(HttpURLConnection.HTTP_CREATED); response.setBody("TODO"); server.enqueue(response); server.start(); final ZooniverseClient client = createZooniverseClient(server); //SyncAdapter.doUploadSync() adds an "interface" parameter too, //but we are testing a more generic API here: final List<HttpUtils.NameValuePair> values = new ArrayList<>(); values.add(new HttpUtils.NameValuePair("classification[subject_ids][]", "504e4a38c499611ea6010c6a")); values.add(new HttpUtils.NameValuePair("classification[favorite][]", "true")); values.add(new HttpUtils.NameValuePair("classification[annotations][0][sloan-0]", "a-0")); values.add(new HttpUtils.NameValuePair("classification[annotations][1][sloan-7]", "a-1")); values.add(new HttpUtils.NameValuePair("classification[annotations][2][sloan-5]", "a-0")); values.add(new HttpUtils.NameValuePair("classification[annotations][3][sloan-6]", "x-5")); final boolean result = client.uploadClassificationSync("testAuthName", "testAuthApiKey", TEST_GROUP_ID, values); assertTrue(result); assertEquals(1, server.getRequestCount()); //This is really just a regression test, //so we notice if something changes unexpectedly: final RecordedRequest request = server.takeRequest(); assertEquals("POST", request.getMethod()); assertEquals("/workflows/" + TEST_GROUP_ID + "/classifications", request.getPath()); assertNotNull(request.getHeader("Authorization")); assertEquals("application/x-www-form-urlencoded", request.getHeader("Content-Type")); final Buffer contents = request.getBody(); final String strContents = contents.readUtf8(); assertEquals("classification%5Bsubject_ids%5D%5B%5D=504e4a38c499611ea6010c6a&classification%5Bfavorite%5D%5B%5D=true&classification%5Bannotations%5D%5B0%5D%5Bsloan-0%5D=a-0&classification%5Bannotations%5D%5B1%5D%5Bsloan-7%5D=a-1&classification%5Bannotations%5D%5B2%5D%5Bsloan-5%5D=a-0&classification%5Bannotations%5D%5B3%5D%5Bsloan-6%5D=x-5", strContents); server.shutdown(); }
Example 19
Source File: Dhis2MockServer.java From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License | 4 votes |
public void enqueueMockResponse(int code, String response) { MockResponse mockResponse = new MockResponse(); mockResponse.setResponseCode(code); mockResponse.setBody(response); server.enqueue(mockResponse); }
Example 20
Source File: MatchableCall.java From RESTMock with Apache License 2.0 | 3 votes |
/** * <p>Makes this {@code MatchableCall} return given {@code responseStrings} responses (one by one) with the specified {@code * responseCode} as a * http status code</p> * * <p>This {@code MatchableCall} will be automatically scheduled within the {@code RESTMockServer} if you want to prevent that, see * {@link MatchableCall#dontSet()}</p> * * <p>If you specify more than one response, each consecutive call to server will return next response from the list, if number of * requests exceeds number of specified responses, the last response will be repeated</p> * * @param responseCode a http response code to use for the response. * @param responseStrings strings to return for this matchableCall's request one for each consecutive request, last string * will be returned for all requests exceeding number of defined responses. * @return this {@code MatchableCall} */ public MatchableCall thenReturnString(int responseCode, String... responseStrings) { MockResponse[] mockResponses = new MockResponse[responseStrings.length]; int i = 0; for (String responseString : responseStrings) { MockResponse response = new MockResponse(); response.setBody(responseString); response.setResponseCode(responseCode); mockResponses[i++] = response; } return thenReturn(mockResponses); }