Java Code Examples for okhttp3.mockwebserver.MockWebServer

The following are top voted examples for showing how to use okhttp3.mockwebserver.MockWebServer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: DisconnectTest.java   Source Code and License 7 votes vote down vote up
@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();
}
 
Example 2
Project: GitHub   File: ThreadInterruptTest.java   Source Code and License 7 votes vote down vote up
@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();
}
 
Example 3
Project: smart-lens   File: InfoActivityTest.java   Source Code and License 7 votes vote down vote up
@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();
}
 
Example 4
Project: GitHub   File: ThreadInterruptTest.java   Source Code and License 7 votes vote down vote up
@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();
}
 
Example 5
Project: GitHub   File: HttpUrlFetcherServerTest.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 6
Project: GitHub   File: JsonQueryParameters.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 7
Project: retryable-retrofit   File: RetryableCallsTest.java   Source Code and License 6 votes vote down vote up
@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>");
  }
}
 
Example 8
Project: firefox-tv   File: CustomTabTest.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 9
Project: GitHub   File: CookiesTest.java   Source Code and License 6 votes vote down vote up
@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"));
}
 
Example 10
Project: GitHub   File: CookiesTest.java   Source Code and License 6 votes vote down vote up
@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"));
}
 
Example 11
Project: GitHub   File: CookiesTest.java   Source Code and License 6 votes vote down vote up
@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"));
}
 
Example 12
Project: GitHub   File: HttpUrlFetcherServerTest.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 13
Project: smart-lens   File: InfoActivityTest.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 14
Project: JavaSDK   File: ServiceInvokerTest.java   Source Code and License 6 votes vote down vote up
@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("{}"));
}
 
Example 15
Project: GitHub   File: CookiesTest.java   Source Code and License 6 votes vote down vote up
@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"));
}
 
Example 16
Project: GitHub   File: DisconnectTest.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 17
Project: GitHub   File: Benchmark.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 18
Project: GitHub   File: JsonAndXmlConverters.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 19
Project: civify-app   File: IssueDetailsTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 20
Project: civify-app   File: RewardsFragmentTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws ParseException {
    sMockWebServer = new MockWebServer();
    try {
        sMockWebServer.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
            .setDateFormat(ServiceGenerator.RAILS_DATE_FORMAT)
            .create();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(sMockWebServer.url("").toString())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
    IssueService issueService = retrofit.create(IssueService.class);
    IssueAdapter issueAdapter =
            AdapterFactory.getInstance().getIssueAdapter(getTargetContext());
    issueAdapter.setService(issueService);
}
 
Example 21
Project: civify-app   File: AwardAdapterImplTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws IOException, ParseException {
    setUpAward();
    mMockWebServer = new MockWebServer();
    mMockWebServer.start();
    mGson = new GsonBuilder()
            .excludeFieldsWithoutExposeAnnotation()
            .setDateFormat(ServiceGenerator.RAILS_DATE_FORMAT)
            .create();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(mMockWebServer.url("").toString())
            .addConverterFactory(GsonConverterFactory.create(mGson)).build();
    AwardService awardService = retrofit.create(AwardService.class);
    SharedPreferences sharedPreferences = mock(SharedPreferences.class);
    mListAwardsSimpleCallbackMock = mock(ListAwardsSimpleCallback.class);
    mAwardSimpleCallbackMock = mock(AwardSimpleCallback.class);
    mAwardAdapter = new AwardAdapterImpl(awardService, sharedPreferences);
    mListExchangedAwardSimpleCallback = mock(ListExchangedAwardSimpleCallback.class);
}
 
Example 22
Project: civify-app   File: LoginAdapterImplTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    mMockServer = new MockWebServer();
    mMockServer.start();
    Retrofit retrofit = (new Retrofit.Builder().baseUrl(mMockServer.url("").toString())
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())).build();
    CivifyLoginService civifyLoginService = retrofit.create(CivifyLoginService.class);
    CivifyMeService civifyMeService = retrofit.create(CivifyMeService.class);
    SharedPreferences.Editor editor = mock(SharedPreferences.Editor.class);
    mSharedPreferences = mock(SharedPreferences.class);
    mLoginFinishedCallbackMock = mock(LoginFinishedCallback.class);
    when(mSharedPreferences.edit()).thenReturn(editor);
    mUser = new User("username", "name", "surname",
            "email", "password", "password");
    mLoginAdapter =
            new LoginAdapterImpl(civifyLoginService, civifyMeService, mSharedPreferences);
}
 
Example 23
Project: retrofit-metrics   File: TimedCallAdapterFactoryTest.java   Source Code and License 6 votes vote down vote up
@Before
public void before() throws IOException {
    metrics = new MetricRegistry();
    server = new MockWebServer();
    server.start();

    MockResponse response = new MockResponse();
    response.setBody(RESPONSE_BODY);
    server.enqueue(response);

    retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(new TimedCallAdapterFactory(metrics))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .baseUrl(server.url("/").toString())
            .build();
}
 
Example 24
Project: chaosflix-leanback   File: MediaApiServiceTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void setup() throws IOException, TimeoutException {
	server = new MockWebServer();
	server.start();
	serverUrl = server.url("").toString();

	Intent s = new Intent(InstrumentationRegistry.getTargetContext(),
			MediaApiService.class);
	s.putExtra(MediaApiService.RECORDING_URL,serverUrl);
	s.putExtra(MediaApiService.STREAMING_URL,serverUrl);
	IBinder binder = mServiceRule.bindService(s);
	service = ((MediaApiService.LocalBinder) binder).getService();
}
 
Example 25
Project: firefox-tv   File: AddtoHSTest.java   Source Code and License 6 votes vote down vote up
@Override
protected void beforeActivityLaunched() {
    super.beforeActivityLaunched();

    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.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("plain_test.html")));

        webServer.start();
    } catch (IOException e) {
        throw new AssertionError("Could not start web server", e);
    }
}
 
Example 26
Project: GitHub   File: VolleyStreamFetcherServerTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws IOException {
  MockitoAnnotations.initMocks(this);

  waitForResponseLatch = new CountDownLatch(1);
  doAnswer(new CountDown()).when(callback).onDataReady(any(InputStream.class));
  doAnswer(new CountDown()).when(callback).onLoadFailed(any(Exception.class));
  requestQueue = Volley.newRequestQueue(RuntimeEnvironment.application);
  mockWebServer = new MockWebServer();
  mockWebServer.start();

  streamCaptor = ArgumentCaptor.forClass(InputStream.class);
}
 
Example 27
Project: google-oauth-authorization-plugin   File: GoogleApiClientTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    initMocks(this);

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

    when(googleConfiguration.clientId()).thenReturn("client-id");
    when(googleConfiguration.clientSecret()).thenReturn("client-secret");

    CallbackURL.instance().updateRedirectURL("callback-url");

    googleApiClient = new GoogleApiClient(googleConfiguration);
}
 
Example 28
Project: GitHub   File: HomePresenterTest.java   Source Code and License 5 votes vote down vote up
@Before public void beforeEachTest() throws Exception {
  mockWebServer = new MockWebServer();
  mockWebServer.start();

  // Set the apps url to the local mock server
  DependencyInjection.BASE_URL = mockWebServer.url("").toString();
}
 
Example 29
Project: GitHub   File: AnnotatedConverters.java   Source Code and License 5 votes vote down vote up
public static void main(String... args) throws IOException {
  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse().setBody("{\"name\": \"Moshi\"}"));
  server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));
  server.enqueue(new MockResponse().setBody("<user name=\"SimpleXML\"/>"));
  server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));

  com.squareup.moshi.Moshi moshi = new com.squareup.moshi.Moshi.Builder().build();
  com.google.gson.Gson gson = new GsonBuilder().create();
  MoshiConverterFactory moshiConverterFactory = MoshiConverterFactory.create(moshi);
  GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson);
  SimpleXmlConverterFactory simpleXmlConverterFactory = SimpleXmlConverterFactory.create();
  Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
      .addConverterFactory(
          new AnnotatedConverterFactory.Builder().add(Moshi.class, moshiConverterFactory)
              .add(Gson.class, gsonConverterFactory)
              .add(SimpleXml.class, simpleXmlConverterFactory)
              .build())
      .addConverterFactory(gsonConverterFactory)
      .build();
  Service service = retrofit.create(Service.class);

  Library library1 = service.exampleMoshi().execute().body();
  System.out.println("Library 1: " + library1.name);

  Library library2 = service.exampleGson().execute().body();
  System.out.println("Library 2: " + library2.name);

  Library library3 = service.exampleSimpleXml().execute().body();
  System.out.println("Library 3: " + library3.name);

  Library library4 = service.exampleDefault().execute().body();
  System.out.println("Library 4: " + library4.name);

  server.shutdown();
}
 
Example 30
Project: GitHub   File: DeserializeErrorBody.java   Source Code and License 5 votes vote down vote up
public static void main(String... args) throws IOException {
  // Create a local web server which response with a 404 and JSON body.
  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse()
      .setResponseCode(404)
      .setBody("{\"message\":\"Unable to locate resource\"}"));

  // Create our Service instance with a Retrofit pointing at the local web server and Gson.
  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(server.url("/"))
      .addConverterFactory(GsonConverterFactory.create())
      .build();
  Service service = retrofit.create(Service.class);

  Response<User> response = service.getUser().execute();

  // Normally you would check response.isSuccess() here before doing the following, but we know
  // this call will always fail. You could also use response.code() to determine whether to
  // convert the error body and/or which type to use for conversion.

  // Look up a converter for the Error type on the Retrofit instance.
  Converter<ResponseBody, Error> errorConverter =
      retrofit.responseBodyConverter(Error.class, new Annotation[0]);
  // Convert the error body into our Error type.
  Error error = errorConverter.convert(response.errorBody());
  System.out.println("ERROR: " + error.message);

  server.shutdown();
}
 
Example 31
Project: GitHub   File: ChunkingConverter.java   Source Code and License 5 votes vote down vote up
public static void main(String... args) throws IOException, InterruptedException {
  MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse());
  server.enqueue(new MockResponse());
  server.start();

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

  Repo retrofitRepo = new Repo("square", "retrofit");

  service.sendNormal(retrofitRepo).execute();
  RecordedRequest normalRequest = server.takeRequest();
  System.out.println(
      "Normal @Body Transfer-Encoding: " + normalRequest.getHeader("Transfer-Encoding"));

  service.sendChunked(retrofitRepo).execute();
  RecordedRequest chunkedRequest = server.takeRequest();
  System.out.println(
      "@Chunked @Body Transfer-Encoding: " + chunkedRequest.getHeader("Transfer-Encoding"));

  server.shutdown();
}
 
Example 32
Project: firefox-tv   File: RestartTest.java   Source Code and License 5 votes vote down vote up
@Override
protected void beforeActivityLaunched() {
    super.beforeActivityLaunched();

    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("image_test.html")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("rabbit.jpg")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("download.jpg")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("image_test.html")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("rabbit.jpg")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("download.jpg")));
        webServer.start();
    } catch (IOException e) {
        throw new AssertionError("Could not start web server", e);
    }
}
 
Example 33
Project: GitHub   File: CacheTest.java   Source Code and License 5 votes vote down vote up
private void assertCached(boolean shouldPut, int responseCode) throws Exception {
  int expectedResponseCode = responseCode;

  server = new MockWebServer();
  MockResponse mockResponse = new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
      .setResponseCode(responseCode)
      .setBody("ABCDE")
      .addHeader("WWW-Authenticate: challenge");
  if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
    mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
  } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
    mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
  } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT
      || responseCode == HttpURLConnection.HTTP_RESET) {
    mockResponse.setBody(""); // We forbid bodies for 204 and 205.
  }
  server.enqueue(mockResponse);

  if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
    // 408's are a bit of an outlier because we may repeat the request if we encounter this
    // response code. In this scenario, there are 2 responses: the initial 408 and then the 200
    // because of the retry. We just want to ensure the initial 408 isn't cached.
    expectedResponseCode = 200;
    server.enqueue(new MockResponse()
        .setHeader("Cache-Control", "no-store")
        .setBody("FGHIJ"));
  }

  server.start();

  Request request = new Request.Builder()
      .url(server.url("/"))
      .build();
  Response response = client.newCall(request).execute();
  assertEquals(expectedResponseCode, response.code());

  // Exhaust the content stream.
  response.body().string();

  Response cached = cache.get(request);
  if (shouldPut) {
    assertNotNull(Integer.toString(responseCode), cached);
    cached.body().close();
  } else {
    assertNull(Integer.toString(responseCode), cached);
  }
  server.shutdown(); // tearDown() isn't sufficient; this test starts multiple servers
}
 
Example 34
Project: GitHub   File: CookiesTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testNetscapeResponse() throws Exception {
  CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
  client = client.newBuilder()
      .cookieJar(new JavaNetCookieJar(cookieManager))
      .build();
  MockWebServer server = new MockWebServer();
  server.start();

  HttpUrl urlWithIpAddress = urlWithIpAddress(server, "/path/foo");
  server.enqueue(new MockResponse().addHeader("Set-Cookie: a=android; "
      + "expires=Fri, 31-Dec-9999 23:59:59 GMT; "
      + "path=/path; "
      + "domain=" + urlWithIpAddress.host() + "; "
      + "secure"));
  get(urlWithIpAddress);

  List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
  assertEquals(1, cookies.size());
  HttpCookie cookie = cookies.get(0);
  assertEquals("a", cookie.getName());
  assertEquals("android", cookie.getValue());
  assertEquals(null, cookie.getComment());
  assertEquals(null, cookie.getCommentURL());
  assertEquals(false, cookie.getDiscard());
  assertTrue(cookie.getMaxAge() > 100000000000L);
  assertEquals("/path", cookie.getPath());
  assertEquals(true, cookie.getSecure());
  assertEquals(0, cookie.getVersion());
}
 
Example 35
Project: java-champion-gg-wrapper   File: ChampionGGTest.java   Source Code and License 5 votes vote down vote up
@BeforeAll static void initChampionGGAPI() {
	webServer = new MockWebServer();
	dispatcher = new MockDispatcher();
	webServer.setDispatcher(dispatcher);
	ChampionGGAPIFactory.BASE_URL = webServer.url("/").toString();

	ChampionGGAPIFactory championGGAPIFactory = new ChampionGGAPIFactory(Constants.API_KEY, -1);
	API = championGGAPIFactory.buildChampionGGAPI();
}
 
Example 36
Project: firefox-tv   File: NotificationScreenshots.java   Source Code and License 5 votes vote down vote up
@Before
public void setUpWebServer() throws IOException {
    webServer = new MockWebServer();

    // Test page
    webServer.enqueue(new MockResponse().setBody(TestHelper.readTestAsset("plain_test.html")));
}
 
Example 37
Project: LoginEligibility.Android   File: LEServiceHandlerTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    signal = new CountDownLatch(1);
    server = new MockWebServer();
    server.start(30000);
    baseUrl = "http://" + server.getHostName() + ":" + server.getPort();

    goodConfig = new LEServiceConfiguration();
    goodConfig.captureApplicationId = "somecaptureappid";
    goodConfig.captureClientId = "somecaptureclientid";
    goodConfig.captureFlowName = "someflowname";
    goodConfig.captureFlowLocale = "some-locale";
    goodConfig.captureFlowVersion = "some-version";
    goodConfig.policyCheckerStage = "dev";
    goodConfig.policyCheckerTenant = "some-tenant";
    goodConfig.policyCheckerHost = baseUrl;


    taskHandler = new LEService.LoginEligibilityResultHandler() {
        @Override
        public void onLEServiceSuccess(JSONObject json) {
            testResult = json;
            signal.countDown();
        }

        @Override
        public void onLEServiceFailure(JSONObject json) {
            testResultError = json;
            signal.countDown();
        }
    };
}
 
Example 38
Project: GitHub   File: URLConnectionTest.java   Source Code and License 5 votes vote down vote up
@Override public HttpURLConnection connect(
    MockWebServer server, OkUrlFactory streamHandlerFactory, URL url)
    throws IOException {
  System.setProperty("proxyHost", server.getHostName());
  System.setProperty("proxyPort", Integer.toString(server.getPort()));
  return streamHandlerFactory.open(url);
}
 
Example 39
Project: GitHub   File: URLConnectionTest.java   Source Code and License 5 votes vote down vote up
@Override public HttpURLConnection connect(
    MockWebServer server, OkUrlFactory streamHandlerFactory, URL url)
    throws IOException {
  System.setProperty("http.proxyHost", server.getHostName());
  System.setProperty("http.proxyPort", Integer.toString(server.getPort()));
  return streamHandlerFactory.open(url);
}
 
Example 40
Project: GitHub   File: URLConnectionTest.java   Source Code and License 5 votes vote down vote up
@Override public HttpURLConnection connect(
    MockWebServer server, OkUrlFactory streamHandlerFactory, URL url)
    throws IOException {
  System.setProperty("https.proxyHost", server.getHostName());
  System.setProperty("https.proxyPort", Integer.toString(server.getPort()));
  return streamHandlerFactory.open(url);
}