java类okhttp3.mockwebserver.MockResponse的实例源码

MockedTest.java 文件源码 项目:retrofit-xmlrpc 阅读 19 收藏 0 点赞 0 评论 0
@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();
}
CacheTest.java 文件源码 项目:GitHub 阅读 20 收藏 0 点赞 0 评论 0
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());
}
CacheTest.java 文件源码 项目:GitHub 阅读 25 收藏 0 点赞 0 评论 0
@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());
}
FlowableThrowingTest.java 文件源码 项目:GitHub 阅读 16 收藏 0 点赞 0 评论 0
@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);

}
URLConnectionTest.java 文件源码 项目:GitHub 阅读 21 收藏 0 点赞 0 评论 0
@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);
  }
}
CallTest.java 文件源码 项目:GitHub 阅读 26 收藏 0 点赞 0 评论 0
@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"));
}
FeignTest.java 文件源码 项目:XXXX 阅读 21 收藏 0 点赞 0 评论 0
/**
 * 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());
}
URLConnectionTest.java 文件源码 项目:GitHub 阅读 26 收藏 0 点赞 0 评论 0
@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());
  }
}
MaybeThrowingTest.java 文件源码 项目:GitHub 阅读 32 收藏 0 点赞 0 评论 0
@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);
}
MaybeThrowingTest.java 文件源码 项目:GitHub 阅读 29 收藏 0 点赞 0 评论 0
@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);
}
HttpLoggingInterceptorTest.java 文件源码 项目:GitHub 阅读 15 收藏 0 点赞 0 评论 0
@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();
}
CacheTest.java 文件源码 项目:GitHub 阅读 30 收藏 0 点赞 0 评论 0
@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());
}
ResponseCacheTest.java 文件源码 项目:GitHub 阅读 22 收藏 0 点赞 0 评论 0
@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());
}
CallTest.java 文件源码 项目:GitHub 阅读 30 收藏 0 点赞 0 评论 0
@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());
}
HttpOverHttp2Test.java 文件源码 项目:GitHub 阅读 24 收藏 0 点赞 0 评论 0
@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"));
}
CacheTest.java 文件源码 项目:GitHub 阅读 20 收藏 0 点赞 0 评论 0
@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());
}
URLConnectionTest.java 文件源码 项目:GitHub 阅读 22 收藏 0 点赞 0 评论 0
@Test public void redirectedPostStripsRequestBodyHeaders() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
      .addHeader("Location: /page2"));
  server.enqueue(new MockResponse().setBody("Page 2"));

  connection = urlFactory.open(server.url("/page1").url());
  connection.setDoOutput(true);
  connection.addRequestProperty("Content-Length", "4");
  connection.addRequestProperty("Content-Type", "text/plain; charset=utf-8");
  connection.addRequestProperty("Transfer-Encoding", "identity");
  OutputStream outputStream = connection.getOutputStream();
  outputStream.write("ABCD".getBytes("UTF-8"));
  outputStream.close();
  assertEquals("Page 2", readAscii(connection.getInputStream(), Integer.MAX_VALUE));

  assertEquals("POST /page1 HTTP/1.1", server.takeRequest().getRequestLine());

  RecordedRequest page2 = server.takeRequest();
  assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
  assertNull(page2.getHeader("Content-Length"));
  assertNull(page2.getHeader("Content-Type"));
  assertNull(page2.getHeader("Transfer-Encoding"));
}
HttpOverHttp2Test.java 文件源码 项目:GitHub 阅读 19 收藏 0 点赞 0 评论 0
@Test public void readAfterLastByte() throws Exception {
  server.enqueue(new MockResponse().setBody("ABC"));

  Call call = client.newCall(new Request.Builder()
      .url(server.url("/"))
      .build());
  Response response = call.execute();

  InputStream in = response.body().byteStream();
  assertEquals('A', in.read());
  assertEquals('B', in.read());
  assertEquals('C', in.read());
  assertEquals(-1, in.read());
  assertEquals(-1, in.read());

  in.close();
}
ResponseCacheTest.java 文件源码 项目:GitHub 阅读 30 收藏 0 点赞 0 评论 0
/**
 * Equivalent to {@code CacheTest.postInvalidatesCacheWithUncacheableResponse()} but demonstrating
 * that {@link ResponseCache} provides no mechanism for cache invalidation as the result of
 * locally-made requests. In reality invalidation could take place from other clients at any
 * time.
 */
@Test public void postInvalidatesCacheWithUncacheableResponse() throws Exception {
  // 1. seed the cache
  // 2. invalidate it with uncacheable response
  // 3. the cache to return the original value
  server.enqueue(new MockResponse()
      .setBody("A")
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)));
  server.enqueue(new MockResponse()
      .setBody("B")
      .setResponseCode(500));

  URL url = server.url("/").url();

  assertEquals("A", readAscii(openConnection(url)));

  HttpURLConnection invalidate = openConnection(url);
  invalidate.setRequestMethod("POST");
  addRequestBodyIfNecessary("POST", invalidate);
  assertEquals("B", readAscii(invalidate));

  assertEquals("A", readAscii(openConnection(url)));
}
EventListenerTest.java 文件源码 项目:GitHub 阅读 26 收藏 0 点赞 0 评论 0
@Test public void failedCallEventSequence() throws IOException {
  server.enqueue(new MockResponse().setBodyDelay(2, TimeUnit.SECONDS));

  client = client.newBuilder().readTimeout(250, TimeUnit.MILLISECONDS).build();

  Call call = client.newCall(new Request.Builder()
      .url(server.url("/"))
      .build());
  try {
    call.execute();
    fail();
  } catch (IOException expected) {
    assertThat(expected.getMessage(), either(equalTo("timeout")).or(equalTo("Read timed out")));
  }

  List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd",
      "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
      "RequestHeadersEnd", "ResponseHeadersStart", "ConnectionReleased", "CallFailed");
  assertEquals(expectedEvents, listener.recordedEventTypes());
}
ResponseCacheTest.java 文件源码 项目:GitHub 阅读 25 收藏 0 点赞 0 评论 0
@Test public void varyMatchesChangedRequestHeaderField() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Cache-Control: max-age=60")
      .addHeader("Vary: Accept-Language")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  URL url = server.url("/").url();
  HttpURLConnection frenchConnection = openConnection(url);
  frenchConnection.setRequestProperty("Accept-Language", "fr-CA");
  assertEquals("A", readAscii(frenchConnection));

  HttpURLConnection englishConnection = openConnection(url);
  englishConnection.setRequestProperty("Accept-Language", "en-US");
  assertEquals("B", readAscii(englishConnection));
}
FeignBuilderTest.java 文件源码 项目:XXXX 阅读 18 收藏 0 点赞 0 评论 0
@Test
public void testProvideInvocationHandlerFactory() throws Exception {
  server.enqueue(new MockResponse().setBody("response data"));

  String url = "http://localhost:" + server.getPort();

  final AtomicInteger callCount = new AtomicInteger();
  InvocationHandlerFactory factory = new InvocationHandlerFactory() {
    private final InvocationHandlerFactory delegate = new Default();

    @Override
    public InvocationHandler create(Target target, Map<Method, MethodHandler> dispatch) {
      callCount.incrementAndGet();
      return delegate.create(target, dispatch);
    }
  };

  TestInterface api =
      Feign.builder().invocationHandlerFactory(factory).target(TestInterface.class, url);
  Response response = api.codecPost("request data");
  assertEquals("response data", Util.toString(response.body().asReader()));
  assertEquals(1, callCount.get());

  assertThat(server.takeRequest())
      .hasBody("request data");
}
HttpOverHttp2Test.java 文件源码 项目:GitHub 阅读 19 收藏 0 点赞 0 评论 0
@Test public void recoverFromOneRefusedStreamReusesConnection() throws Exception {
  server.enqueue(new MockResponse()
      .setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
      .setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode));
  server.enqueue(new MockResponse()
      .setBody("abc"));

  Call call = client.newCall(new Request.Builder()
      .url(server.url("/"))
      .build());
  Response response = call.execute();
  assertEquals("abc", response.body().string());

  assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection.
  assertEquals(1, server.takeRequest().getSequenceNumber()); // Reused connection.
}
RewardsFragmentTest.java 文件源码 项目:civify-app 阅读 18 收藏 0 点赞 0 评论 0
private Award mockAward() throws ParseException {
    String dateString = "2016-12-21T20:08:11.000Z";
    DateFormat dateFormat =
            new SimpleDateFormat(ServiceGenerator.RAILS_DATE_FORMAT, Locale.getDefault());
    Date date = dateFormat.parse(dateString);

    Picture picture =
            new Picture("picture-file-name", "picture-content-type", "picture-content");
    picture.setBaseUrl(MOCK_BASE_URL);
    picture.setSmallUrl(MOCK_IMAGE_URL);
    picture.setMedUrl(MOCK_IMAGE_URL);
    picture.setLargeUrl(MOCK_IMAGE_URL);

    MockResponse mockResponse = new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);
    sMockWebServer.enqueue(mockResponse);

    return new Award("award-title", "award-description", 35, date, date, "award-auth-token",
            "commerce-name", picture);
}
URLConnectionTest.java 文件源码 项目:GitHub 阅读 29 收藏 0 点赞 0 评论 0
/**
 * We had a bug where we weren't closing Gzip streams on redirects.
 * https://github.com/square/okhttp/issues/441
 */
@Test public void gzipWithRedirectAndConnectionReuse() throws Exception {
  server.enqueue(new MockResponse()
      .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
      .addHeader("Location: /foo")
      .addHeader("Content-Encoding: gzip")
      .setBody(gzip("Moved! Moved! Moved!")));
  server.enqueue(new MockResponse().setBody("This is the new page!"));

  HttpURLConnection connection = urlFactory.open(server.url("/").url());
  assertContent("This is the new page!", connection);

  RecordedRequest requestA = server.takeRequest();
  assertEquals(0, requestA.getSequenceNumber());

  RecordedRequest requestB = server.takeRequest();
  assertEquals(1, requestB.getSequenceNumber());
}
ConnectionReuseTest.java 文件源码 项目:GitHub 阅读 24 收藏 0 点赞 0 评论 0
@Test public void connectionsReusedWithRedirectEvenIfPoolIsSizeZero() throws Exception {
  client = client.newBuilder()
      .connectionPool(new ConnectionPool(0, 5, TimeUnit.SECONDS))
      .build();
  server.enqueue(new MockResponse()
      .setResponseCode(301)
      .addHeader("Location: /b")
      .setBody("a"));
  server.enqueue(new MockResponse().setBody("b"));

  Request request = new Request.Builder()
      .url(server.url("/"))
      .build();
  Response response = client.newCall(request).execute();
  assertEquals("b", response.body().string());
  assertEquals(0, server.takeRequest().getSequenceNumber());
  assertEquals(1, server.takeRequest().getSequenceNumber());
}
CallTest.java 文件源码 项目:GitHub 阅读 25 收藏 0 点赞 0 评论 0
@Test public void post() throws Exception {
  server.enqueue(new MockResponse().setBody("abc"));

  Request request = new Request.Builder()
      .url(server.url("/"))
      .post(RequestBody.create(MediaType.parse("text/plain"), "def"))
      .build();

  executeSynchronously(request)
      .assertCode(200)
      .assertBody("abc");

  RecordedRequest recordedRequest = server.takeRequest();
  assertEquals("POST", recordedRequest.getMethod());
  assertEquals("def", recordedRequest.getBody().readUtf8());
  assertEquals("3", recordedRequest.getHeader("Content-Length"));
  assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type"));
}
WebSocketHttpTest.java 文件源码 项目:GitHub 阅读 21 收藏 0 点赞 0 评论 0
@Test public void closeReasonTooLong() throws IOException {
  webServer.enqueue(new MockResponse().withWebSocketUpgrade(serverListener));

  WebSocket webSocket = newWebSocket();
  WebSocket server = serverListener.assertOpen();

  clientListener.assertOpen();
  String reason = repeat('X', 124);
  try {
    webSocket.close(1000, reason);
    fail();
  } catch (IllegalArgumentException expected) {
    assertEquals("reason.size() > 123: " + reason, expected.getMessage());
  }

  webSocket.close(1000, null);
  serverListener.assertClosing(1000, "");

  server.close(1000, null);
  clientListener.assertClosing(1000, "");
  clientListener.assertClosed(1000, "");

  serverListener.assertClosed(1000, "");
}
AbstractOkHttpTest.java 文件源码 项目:java-okhttp 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void testParentSpanSource() throws IOException {
    {
        Scope parent = mockTracer.buildSpan("parent")
                .startActive(true);

        mockWebServer.enqueue(new MockResponse()
                .setResponseCode(203));

        Request request = new Request.Builder()
                .url(mockWebServer.url("bar"))
                .tag(new TagWrapper(parent.span().context()))
                .get()
                .build();

        client.newCall(request).execute();
        parent.close();
    }

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    assertOnErrors(mockSpans);
    Assert.assertEquals(3, mockSpans.size());
    Assert.assertEquals(mockSpans.get(2).context().traceId(), mockSpans.get(1).context().traceId());
    Assert.assertEquals(mockSpans.get(2).context().spanId(), mockSpans.get(1).parentId());
}
SetterFactoryTest.java 文件源码 项目:XXXX 阅读 18 收藏 0 点赞 0 评论 0
@Test
  public void customSetter() {
    thrown.expect(HystrixRuntimeException.class);
    thrown.expectMessage("POST / failed and no fallback available.");

    server.enqueue(new MockResponse().setResponseCode(500));

SetterFactory commandKeyIsRequestLine = (target, method) -> {
  String groupKey = target.name();
  String commandKey = method.getAnnotation(RequestLine.class).value();
  return HystrixCommand.Setter
      .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
      .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
};

    TestInterface api = HystrixFeign.builder()
        .setterFactory(commandKeyIsRequestLine)
        .target(TestInterface.class, "http://localhost:" + server.getPort());

    api.invoke();
  }


问题


面经


文章

微信
公众号

扫码关注公众号