當前位置: 首頁>>代碼示例>>Java>>正文


Java MockResponse類代碼示例

本文整理匯總了Java中okhttp3.mockwebserver.MockResponse的典型用法代碼示例。如果您正苦於以下問題:Java MockResponse類的具體用法?Java MockResponse怎麽用?Java MockResponse使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


MockResponse類屬於okhttp3.mockwebserver包,在下文中一共展示了MockResponse類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: listMethods

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test
public void listMethods() throws IOException, InterruptedException {
    server.enqueue(new MockResponse()
            .addHeader("Content-Type", "application/xml; charset=UTF-8")
            .setBody("<?xml version=\"1.0\"?>\n" +
                    "<methodResponse>\n" +
                    "  <params>\n" +
                    "    <param>\n" +
                    "        <value>" +
                    "            <array>" +
                    "                <data>" +
                    "                    <value><string>system.listMethods</string></value>\n" +
                    "                    <value><string>multiply</string></value>\n" +
                    "                </data>" +
                    "            </array>" +
                    "        </value>" +
                    "    </param>\n" +
                    "  </params>\n" +
                    "</methodResponse>"));

    TestService service = retrofit.create(TestService.class);
    String[] execute = service.listMethods(NOTHING).execute().body();
    server.takeRequest();
    assertThat(execute).isNotEmpty();
}
 
開發者ID:erickok,項目名稱:retrofit-xmlrpc,代碼行數:26,代碼來源:MockedTest.java

示例2: temporaryRedirectCachedWithCachingHeader

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
private void temporaryRedirectCachedWithCachingHeader(
    int responseCode, String headerName, String headerValue) throws Exception {
  server.enqueue(new MockResponse()
      .setResponseCode(responseCode)
      .addHeader(headerName, headerValue)
      .addHeader("Location", "/a"));
  server.enqueue(new MockResponse()
      .addHeader(headerName, headerValue)
      .setBody("a"));
  server.enqueue(new MockResponse()
      .setBody("b"));
  server.enqueue(new MockResponse()
      .setBody("c"));

  HttpUrl url = server.url("/");
  assertEquals("a", get(url).body().string());
  assertEquals("a", get(url).body().string());
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:19,代碼來源:CacheTest.java

示例3: varyMultipleFieldValuesWithMatch

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void varyMultipleFieldValuesWithMatch() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Cache-Control: max-age=60")
      .addHeader("Vary: Accept-Language")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  HttpUrl url = server.url("/");
  Request request1 = new Request.Builder()
      .url(url)
      .addHeader("Accept-Language", "fr-CA, fr-FR")
      .addHeader("Accept-Language", "en-US")
      .build();
  Response response1 = client.newCall(request1).execute();
  assertEquals("A", response1.body().string());

  Request request2 = new Request.Builder()
      .url(url)
      .addHeader("Accept-Language", "fr-CA, fr-FR")
      .addHeader("Accept-Language", "en-US")
      .build();
  Response response2 = client.newCall(request2).execute();
  assertEquals("A", response2.body().string());
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:26,代碼來源:CacheTest.java

示例4: bodyThrowingInOnCompleteDeliveredToPlugin

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void bodyThrowingInOnCompleteDeliveredToPlugin() {
  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<String> subscriber = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.body().subscribe(new ForwardingSubscriber<String>(subscriber) {
    @Override public void onComplete() {
      throw e;
    }
  });

  subscriber.assertAnyValue();
  assertThat(throwableRef.get()).isSameAs(e);

}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:25,代碼來源:FlowableThrowingTest.java

示例5: connectViaHttpsWithSSLFallbackFailuresRecorded

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void connectViaHttpsWithSSLFallbackFailuresRecorded() throws Exception {
  server.useHttps(sslClient.socketFactory, false);
  server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE));
  server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE));

  urlFactory.setClient(urlFactory.client().newBuilder()
      .dns(new SingleInetAddressDns())
      .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS))
      .hostnameVerifier(new RecordingHostnameVerifier())
      .sslSocketFactory(suppressTlsFallbackClientSocketFactory(), sslClient.trustManager)
      .build());
  connection = urlFactory.open(server.url("/foo").url());

  try {
    connection.getResponseCode();
    fail();
  } catch (IOException expected) {
    assertEquals(1, expected.getSuppressed().length);
  }
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:21,代碼來源:URLConnectionTest.java

示例6: get_Async

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void get_Async() throws Exception {
  server.enqueue(new MockResponse()
      .setBody("abc")
      .addHeader("Content-Type: text/plain"));

  Request request = new Request.Builder()
      .url(server.url("/"))
      .header("User-Agent", "AsyncApiTest")
      .build();
  client.newCall(request).enqueue(callback);

  callback.await(request.url())
      .assertCode(200)
      .assertHeader("Content-Type", "text/plain")
      .assertBody("abc");

  assertEquals("AsyncApiTest", server.takeRequest().getHeader("User-Agent"));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:19,代碼來源:CallTest.java

示例7: bodyTypeCorrespondsWithParameterType

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
/**
 * The type of a parameter value may not be the desired type to encode as. Prefer the interface
 * type.
 */
@Test
public void bodyTypeCorrespondsWithParameterType() throws Exception {
  server.enqueue(new MockResponse().setBody("foo"));

  final AtomicReference<Type> encodedType = new AtomicReference<Type>();
  TestInterface api = new TestInterfaceBuilder()
      .encoder(new Encoder.Default() {
        @Override
        public void encode(Object object, Type bodyType, RequestTemplate template) {
          encodedType.set(bodyType);
        }
      })
      .target("http://localhost:" + server.getPort());

  api.body(Arrays.asList("netflix", "denominator", "password"));

  server.takeRequest();

  assertThat(encodedType.get()).isEqualTo(new TypeToken<List<String>>() {
  }.getType());
}
 
開發者ID:wenwu315,項目名稱:XXXX,代碼行數:26,代碼來源:FeignTest.java

示例8: doesNotAttemptAuthorization21Times

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void doesNotAttemptAuthorization21Times() throws Exception {
  for (int i = 0; i < 21; i++) {
    server.enqueue(new MockResponse().setResponseCode(401));
  }

  String credential = Credentials.basic("jesse", "peanutbutter");
  urlFactory.setClient(urlFactory.client().newBuilder()
      .authenticator(new RecordingOkAuthenticator(credential))
      .build());

  connection = urlFactory.open(server.url("/").url());
  try {
    connection.getInputStream();
    fail();
  } catch (ProtocolException expected) {
    assertEquals(401, connection.getResponseCode());
    assertEquals("Too many follow-up requests: 21", expected.getMessage());
  }
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:20,代碼來源:URLConnectionTest.java

示例9: responseThrowingInOnSuccessDeliveredToPlugin

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void responseThrowingInOnSuccessDeliveredToPlugin() {
  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);
      }
    }
  });

  RecordingMaybeObserver<Response<String>> observer = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.response().subscribe(new ForwardingObserver<Response<String>>(observer) {
    @Override public void onSuccess(Response<String> value) {
      throw e;
    }
  });

  assertThat(throwableRef.get()).isSameAs(e);
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:23,代碼來源:MaybeThrowingTest.java

示例10: basicPost

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void basicPost() throws IOException {
  setLevel(Level.BASIC);

  server.enqueue(new MockResponse());
  client.newCall(request().post(RequestBody.create(PLAIN, "Hi?")).build()).execute();

  applicationLogs
      .assertLogEqual("--> POST " + url + " (3-byte body)")
      .assertLogMatch("<-- 200 OK " + url + " \\(\\d+ms, 0-byte body\\)")
      .assertNoMoreLogs();

  networkLogs
      .assertLogEqual("--> POST " + url + " http/1.1 (3-byte body)")
      .assertLogMatch("<-- 200 OK " + url + " \\(\\d+ms, 0-byte body\\)")
      .assertNoMoreLogs();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:17,代碼來源:HttpLoggingInterceptorTest.java

示例11: requestMaxStaleNotHonoredWithMustRevalidate

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void requestMaxStaleNotHonoredWithMustRevalidate() throws IOException {
  server.enqueue(new MockResponse()
      .setBody("A")
      .addHeader("Cache-Control: max-age=120, must-revalidate")
      .addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES)));
  server.enqueue(new MockResponse()
      .setBody("B"));

  assertEquals("A", get(server.url("/")).body().string());

  Request request = new Request.Builder()
      .url(server.url("/"))
      .header("Cache-Control", "max-stale=180")
      .build();
  Response response = client.newCall(request).execute();
  assertEquals("B", response.body().string());
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:18,代碼來源:CacheTest.java

示例12: secureResponseCaching

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void secureResponseCaching() throws IOException {
  assumeFalse(getPlatform().equals("jdk9"));

  server.useHttps(sslClient.socketFactory, false);
  server.enqueue(new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
      .setBody("ABC"));

  HttpsURLConnection c1 = (HttpsURLConnection) openConnection(server.url("/").url());
  c1.setSSLSocketFactory(sslClient.socketFactory);
  c1.setHostnameVerifier(hostnameVerifier);
  assertEquals("ABC", readAscii(c1));

  // OpenJDK 6 fails on this line, complaining that the connection isn't open yet
  String suite = c1.getCipherSuite();
  List<Certificate> localCerts = toListOrNull(c1.getLocalCertificates());
  List<Certificate> serverCerts = toListOrNull(c1.getServerCertificates());
  Principal peerPrincipal = c1.getPeerPrincipal();
  Principal localPrincipal = c1.getLocalPrincipal();

  HttpsURLConnection c2 = (HttpsURLConnection) openConnection(server.url("/").url()); // cached!
  c2.setSSLSocketFactory(sslClient.socketFactory);
  c2.setHostnameVerifier(hostnameVerifier);
  assertEquals("ABC", readAscii(c2));

  assertEquals(suite, c2.getCipherSuite());
  assertEquals(localCerts, toListOrNull(c2.getLocalCertificates()));
  assertEquals(serverCerts, toListOrNull(c2.getServerCertificates()));
  assertEquals(peerPrincipal, c2.getPeerPrincipal());
  assertEquals(localPrincipal, c2.getLocalPrincipal());
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:33,代碼來源:ResponseCacheTest.java

示例13: reusedSourcesGetIndependentTimeoutInstances

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void reusedSourcesGetIndependentTimeoutInstances() throws Exception {
  server.enqueue(new MockResponse().setBody("abc"));
  server.enqueue(new MockResponse().setBody("def"));

  // Call 1: set a deadline on the response body.
  Request request1 = new Request.Builder().url(server.url("/")).build();
  Response response1 = client.newCall(request1).execute();
  BufferedSource body1 = response1.body().source();
  assertEquals("abc", body1.readUtf8());
  body1.timeout().deadline(5, TimeUnit.SECONDS);

  // Call 2: check for the absence of a deadline on the request body.
  Request request2 = new Request.Builder().url(server.url("/")).build();
  Response response2 = client.newCall(request2).execute();
  BufferedSource body2 = response2.body().source();
  assertEquals("def", body2.readUtf8());
  assertFalse(body2.timeout().hasDeadline());

  // Use sequence numbers to confirm the connection was pooled.
  assertEquals(0, server.takeRequest().getSequenceNumber());
  assertEquals(1, server.takeRequest().getSequenceNumber());
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:23,代碼來源:CallTest.java

示例14: noDefaultContentLengthOnStreamingPost

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void noDefaultContentLengthOnStreamingPost() throws Exception {
  final byte[] postBytes = "FGHIJ".getBytes(Util.UTF_8);

  server.enqueue(new MockResponse().setBody("ABCDE"));

  Call call = client.newCall(new Request.Builder()
      .url(server.url("/foo"))
      .post(new RequestBody() {
        @Override public MediaType contentType() {
          return MediaType.parse("text/plain; charset=utf-8");
        }

        @Override public void writeTo(BufferedSink sink) throws IOException {
          sink.write(postBytes);
        }
      })
      .build());

  Response response = call.execute();
  assertEquals("ABCDE", response.body().string());

  RecordedRequest request = server.takeRequest();
  assertEquals("POST /foo HTTP/1.1", request.getRequestLine());
  assertArrayEquals(postBytes, request.getBody().readByteArray());
  assertNull(request.getHeader("Content-Length"));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:27,代碼來源:HttpOverHttp2Test.java

示例15: varyMatchesUnchangedRequestHeaderField

import okhttp3.mockwebserver.MockResponse; //導入依賴的package包/類
@Test public void varyMatchesUnchangedRequestHeaderField() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Cache-Control: max-age=60")
      .addHeader("Vary: Accept-Language")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  HttpUrl url = server.url("/");
  Request request = new Request.Builder()
      .url(url)
      .header("Accept-Language", "fr-CA")
      .build();
  Response response1 = client.newCall(request).execute();
  assertEquals("A", response1.body().string());
  Request request1 = new Request.Builder()
      .url(url)
      .header("Accept-Language", "fr-CA")
      .build();
  Response response2 = client.newCall(request1).execute();
  assertEquals("A", response2.body().string());
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:23,代碼來源:CacheTest.java


注:本文中的okhttp3.mockwebserver.MockResponse類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。