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


Java MockWebServer類代碼示例

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


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

示例1: setUp

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
@Before public void setUp() throws Exception {
  // Sockets on some platforms can have large buffers that mean writes do not block when
  // required. These socket factories explicitly set the buffer sizes on sockets created.
  server = new MockWebServer();
  server.setServerSocketFactory(
      new DelegatingServerSocketFactory(ServerSocketFactory.getDefault()) {
        @Override protected ServerSocket configureServerSocket(
            ServerSocket serverSocket) throws IOException {
          serverSocket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
          return serverSocket;
        }
      });
  client = defaultClient().newBuilder()
      .socketFactory(new DelegatingSocketFactory(SocketFactory.getDefault()) {
        @Override protected Socket configureSocket(Socket socket) throws IOException {
          socket.setSendBufferSize(SOCKET_BUFFER_SIZE);
          socket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
          return socket;
        }
      })
      .build();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:23,代碼來源:DisconnectTest.java

示例2: setUp

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
@Before public void setUp() throws Exception {
  // Sockets on some platforms can have large buffers that mean writes do not block when
  // required. These socket factories explicitly set the buffer sizes on sockets created.
  server = new MockWebServer();
  server.setServerSocketFactory(
      new DelegatingServerSocketFactory(ServerSocketFactory.getDefault()) {
        @Override
        protected ServerSocket configureServerSocket(ServerSocket serverSocket)
            throws IOException {
          serverSocket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
          return serverSocket;
        }
      });
  client = defaultClient().newBuilder()
      .socketFactory(new DelegatingSocketFactory(SocketFactory.getDefault()) {
        @Override
        protected Socket configureSocket(Socket socket) throws IOException {
          socket.setSendBufferSize(SOCKET_BUFFER_SIZE);
          socket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
          return socket;
        }
      })
      .build();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:25,代碼來源:ThreadInterruptTest.java

示例3: checkImageApiResponseFail

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
@Test
public void checkImageApiResponseFail() throws Exception {
    MockWebServer mockWebServer = startMockWebServer();
    //Success response for the info api
    mockWebServer.enqueue(new MockResponse()
            .setResponseCode(200)
            .setBody(getStringFromFile(InstrumentationRegistry.getInstrumentation().getContext(),
                    com.kevalpatel2106.smartlens.test.R.raw.wiki_info_success_response)));
    //Fail response for the image api.
    mockWebServer.enqueue(new MockResponse().setResponseCode(500));
    openActivity();

    //Wait for mock api
    Delay.startDelay(TestConfig.DELAY_FOR_MOCK_API);
    onView(withId(R.id.root_view)).perform(ViewActions.closeSoftKeyboard());

    //Check if there are text?
    assertTrue(mWikiFragmentFragmentTestRule.getActivity().mViewFlipper.getDisplayedChild() ==
            INFO_VIEW);
    onView(withId(R.id.wiki_page_tv)).check(ViewAssertions.matches(CustomMatchers.hasText()));
    onView(withId(R.id.wiki_page_iv)).check(ViewAssertions.matches(not(CustomMatchers.hasImage())));

    Delay.stopDelay();
    mockWebServer.shutdown();
}
 
開發者ID:kevalpatel2106,項目名稱:smart-lens,代碼行數:26,代碼來源:InfoActivityTest.java

示例4: testSetsReadTimeout

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
@Test
public void testSetsReadTimeout() throws Exception {
  MockWebServer tempWebServer = new MockWebServer();
  tempWebServer.enqueue(
      new MockResponse().setBody("test").throttleBody(1, TIMEOUT_TIME_MS, TimeUnit.MILLISECONDS));
  tempWebServer.start();

  try {
    getFetcher().loadData(Priority.HIGH, callback);
  } finally {
    tempWebServer.shutdown();
    // shutdown() called before any enqueue() blocks until it times out.
    mockWebServer.enqueue(new MockResponse().setResponseCode(200));
  }

  verify(callback).onLoadFailed(isA(IOException.class));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:18,代碼來源:HttpUrlFetcherServerTest.java

示例5: main

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
public static void main(String... args) throws IOException, InterruptedException {
  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse());

  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(server.url("/"))
      .addConverterFactory(new JsonStringConverterFactory(GsonConverterFactory.create()))
      .build();
  Service service = retrofit.create(Service.class);

  Call<ResponseBody> call = service.example(new Filter("123"));
  Response<ResponseBody> response = call.execute();
  // TODO handle user response...

  // Print the request path that the server saw to show the JSON query param:
  RecordedRequest recordedRequest = server.takeRequest();
  System.out.println(recordedRequest.getPath());

  server.shutdown();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:22,代碼來源:JsonQueryParameters.java

示例6: retryableCallMustBeParameterized

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
@Test public void retryableCallMustBeParameterized() throws InterruptedException {
  RetryableCalls retryableCalls = new RetryableCalls();
  MockWebServer server = new MockWebServer();
  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(server.url("/"))
      .addCallAdapterFactory(retryableCalls.getFactory())
      .addConverterFactory(new ToStringConverterFactory())
      .build();
  UnparameterizedService service = retrofit.create(UnparameterizedService.class);
  try {
    service.get();
    fail();
  } catch (IllegalArgumentException serviceMethodException) {
    assertThat(serviceMethodException.getCause()).hasMessageThat().isEqualTo(
        "RetryableCall return type must be parameterized "
            + "as RetryableCall<Foo> or RetryableCall<? extends Foo>");
  }
}
 
開發者ID:NightlyNexus,項目名稱:retryable-retrofit,代碼行數:19,代碼來源:RetryableCallsTest.java

示例7: startWebServer

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
private void startWebServer() {
    final Context appContext = InstrumentationRegistry.getInstrumentation()
            .getTargetContext()
            .getApplicationContext();

    PreferenceManager.getDefaultSharedPreferences(appContext)
            .edit()
            .putBoolean(FIRSTRUN_PREF, true)
            .apply();

    webServer = new MockWebServer();

    try {
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("plain_test.html")));
        webServer.start();
    } catch (IOException e) {
        throw new AssertionError("Could not start web server", e);
    }
}
 
開發者ID:mozilla-mobile,項目名稱:firefox-tv,代碼行數:21,代碼來源:CustomTabTest.java

示例8: testSendingCookiesFromStore

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
@Test public void testSendingCookiesFromStore() throws Exception {
  MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse());
  server.start();
  HttpUrl serverUrl = urlWithIpAddress(server, "/");

  CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
  HttpCookie cookieA = new HttpCookie("a", "android");
  cookieA.setDomain(serverUrl.host());
  cookieA.setPath("/");
  cookieManager.getCookieStore().add(serverUrl.uri(), cookieA);
  HttpCookie cookieB = new HttpCookie("b", "banana");
  cookieB.setDomain(serverUrl.host());
  cookieB.setPath("/");
  cookieManager.getCookieStore().add(serverUrl.uri(), cookieB);
  client = client.newBuilder()
      .cookieJar(new JavaNetCookieJar(cookieManager))
      .build();

  get(serverUrl);
  RecordedRequest request = server.takeRequest();

  assertEquals("a=android; b=banana", request.getHeader("Cookie"));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:25,代碼來源:CookiesTest.java

示例9: receiveAndSendMultipleCookies

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
@Test public void receiveAndSendMultipleCookies() throws Exception {
  MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse()
      .addHeader("Set-Cookie", "a=android")
      .addHeader("Set-Cookie", "b=banana"));
  server.enqueue(new MockResponse());
  server.start();

  CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
  client = client.newBuilder()
      .cookieJar(new JavaNetCookieJar(cookieManager))
      .build();

  get(urlWithIpAddress(server, "/"));
  RecordedRequest request1 = server.takeRequest();
  assertNull(request1.getHeader("Cookie"));

  get(urlWithIpAddress(server, "/"));
  RecordedRequest request2 = server.takeRequest();
  assertEquals("a=android; b=banana", request2.getHeader("Cookie"));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:22,代碼來源:CookiesTest.java

示例10: testCookiesSentIgnoresCase

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
@Test public void testCookiesSentIgnoresCase() throws Exception {
  client = client.newBuilder()
      .cookieJar(new JavaNetCookieJar(new CookieManager() {
        @Override public Map<String, List<String>> get(URI uri,
            Map<String, List<String>> requestHeaders) throws IOException {
          Map<String, List<String>> result = new LinkedHashMap<>();
          result.put("COOKIE", Collections.singletonList("Bar=bar"));
          result.put("cooKIE2", Collections.singletonList("Baz=baz"));
          return result;
        }
      }))
      .build();

  MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse());
  server.start();

  get(server.url("/"));

  RecordedRequest request = server.takeRequest();
  assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie"));
  assertNull(request.getHeader("Cookie2"));
  assertNull(request.getHeader("Quux"));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:25,代碼來源:CookiesTest.java

示例11: checkInfoApiResponseFail

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
@Test
public void checkInfoApiResponseFail() throws Exception {
    MockWebServer mockWebServer = startMockWebServer();
    //Fail response for the info api.
    mockWebServer.enqueue(new MockResponse().setResponseCode(500));
    //Success response for the image api.
    mockWebServer.enqueue(new MockResponse()
            .setResponseCode(200)
            .setBody(getStringFromFile(InstrumentationRegistry.getInstrumentation().getContext(),
                    com.kevalpatel2106.smartlens.test.R.raw.wiki_image_success_response)));
    openActivity();

    //Wait for mock api
    Delay.startDelay(TestConfig.DELAY_FOR_MOCK_API);
    onView(withId(R.id.root_view)).perform(ViewActions.closeSoftKeyboard());

    //Check if error occurred?
    assertTrue(mWikiFragmentFragmentTestRule.getActivity().mViewFlipper.getDisplayedChild() ==
            ERROR_VIEW);

    Delay.stopDelay();
    mockWebServer.shutdown();
}
 
開發者ID:kevalpatel2106,項目名稱:smart-lens,代碼行數:24,代碼來源:InfoActivityTest.java

示例12: setUp

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
@BeforeMethod
public void setUp() throws Exception {
  server = new MockWebServer();
  server.start(18080);
  server.enqueue(new MockResponse().setResponseCode(200).setBody("{\n" +
      "  \"access_token\": \"testAccessToken\",\n" +
      "  \"expires_in\": 1,\n" +
      "  \"token_type\": \"Bearer\"\n" +
      "}"));
  server.enqueue(new MockResponse().setResponseCode(401).setBody("{\n" +
      "\"message\": \"Unauthorized\"\n" +
      "}"));
  server.enqueue(new MockResponse().setResponseCode(200).setBody("{\n" +
      "  \"access_token\": \"<Your access token here>\",\n" +
      "  \"expires_in\": 1,\n" +
      "  \"token_type\": \"Bearer\"\n" +
      "}"));
  server.enqueue(new MockResponse().setResponseCode(200).setBody("{}"));
  server.enqueue(new MockResponse().setResponseCode(200).setBody("{}"));
}
 
開發者ID:OpenGamma,項目名稱:JavaSDK,代碼行數:21,代碼來源:ServiceInvokerTest.java

示例13: startServer

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
private MockWebServer startServer() throws IOException {
  Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);
  MockWebServer server = new MockWebServer();

  if (tls) {
    SslClient sslClient = SslClient.localhost();
    server.useHttps(sslClient.socketFactory, false);
    server.setProtocols(protocols);
  }

  final MockResponse response = newResponse();
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      return response;
    }
  });

  server.start();
  return server;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:21,代碼來源:Benchmark.java

示例14: main

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
public static void main(String... args) throws IOException {
  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse().setBody("{\"name\": \"Jason\"}"));
  server.enqueue(new MockResponse().setBody("<user name=\"Eximel\"/>"));

  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(server.url("/"))
      .addConverterFactory(new QualifiedTypeConverterFactory(
          GsonConverterFactory.create(),
          SimpleXmlConverterFactory.create()))
      .build();
  Service service = retrofit.create(Service.class);

  User user1 = service.exampleJson().execute().body();
  System.out.println("User 1: " + user1.name);

  User user2 = service.exampleXml().execute().body();
  System.out.println("User 2: " + user2.name);

  server.shutdown();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:23,代碼來源:JsonAndXmlConverters.java

示例15: setUp

import okhttp3.mockwebserver.MockWebServer; //導入依賴的package包/類
@Before
public void setUp() throws ParseException {
    mMockWebServer = new MockWebServer();
    try {
        mMockWebServer.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
            .setDateFormat(ServiceGenerator.RAILS_DATE_FORMAT)
            .create();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(mMockWebServer.url("").toString())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
    IssueService issueService = retrofit.create(IssueService.class);
    IssueAdapter issueAdapter =
            AdapterFactory.getInstance().getIssueAdapter(getTargetContext());
    issueAdapter.setService(issueService);
}
 
開發者ID:ArnauBlanch,項目名稱:civify-app,代碼行數:20,代碼來源:IssueDetailsTest.java


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