当前位置: 首页>>代码示例>>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;未经允许,请勿转载。