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