Search in sources :

Example 91 with Retrofit

use of retrofit2.Retrofit in project retrofit by square.

the class SimpleMockService method main.

public static void main(String... args) throws IOException {
    // Create a very simple Retrofit adapter which points the GitHub API.
    Retrofit retrofit = new Retrofit.Builder().baseUrl(SimpleService.API_URL).build();
    // Create a MockRetrofit object with a NetworkBehavior which manages the fake behavior of calls.
    NetworkBehavior behavior = NetworkBehavior.create();
    MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit).networkBehavior(behavior).build();
    BehaviorDelegate<GitHub> delegate = mockRetrofit.create(GitHub.class);
    MockGitHub gitHub = new MockGitHub(delegate);
    // Query for some contributors for a few repositories.
    printContributors(gitHub, "square", "retrofit");
    printContributors(gitHub, "square", "picasso");
    // Using the mock-only methods, add some additional data.
    System.out.println("Adding more mock data...\n");
    gitHub.addContributor("square", "retrofit", "Foo Bar", 61);
    gitHub.addContributor("square", "picasso", "Kit Kat", 53);
    // Reduce the delay to make the next calls complete faster.
    behavior.setDelay(500, TimeUnit.MILLISECONDS);
    // Query for the contributors again so we can see the mock data that was added.
    printContributors(gitHub, "square", "retrofit");
    printContributors(gitHub, "square", "picasso");
}
Also used : Retrofit(retrofit2.Retrofit) MockRetrofit(retrofit2.mock.MockRetrofit) MockRetrofit(retrofit2.mock.MockRetrofit) GitHub(com.example.retrofit.SimpleService.GitHub) NetworkBehavior(retrofit2.mock.NetworkBehavior)

Example 92 with Retrofit

use of retrofit2.Retrofit in project retrofit by square.

the class CallTest method responseBodyBuffers.

@Test
public void responseBodyBuffers() throws IOException {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).addConverterFactory(new ToStringConverterFactory()).build();
    Service example = retrofit.create(Service.class);
    server.enqueue(new MockResponse().setBody("1234").setSocketPolicy(DISCONNECT_DURING_RESPONSE_BODY));
    Call<ResponseBody> buffered = example.getBody();
    // When buffering we will detect all socket problems before returning the Response.
    try {
        buffered.execute();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage("unexpected end of stream");
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) IOException(java.io.IOException) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

Example 93 with Retrofit

use of retrofit2.Retrofit in project retrofit by square.

the class CallTest method emptyResponse.

@Test
public void emptyResponse() throws IOException {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).addConverterFactory(new ToStringConverterFactory()).build();
    Service example = retrofit.create(Service.class);
    server.enqueue(new MockResponse().setBody("").addHeader("Content-Type", "text/stringy"));
    Response<String> response = example.getString().execute();
    assertThat(response.body()).isEqualTo("");
    ResponseBody rawBody = response.raw().body();
    assertThat(rawBody.contentLength()).isEqualTo(0);
    assertThat(rawBody.contentType().toString()).isEqualTo("text/stringy");
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

Example 94 with Retrofit

use of retrofit2.Retrofit in project retrofit by square.

the class CallTest method conversionProblemIncomingMaskedByConverterIsUnwrapped.

@Test
public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException {
    // MWS has no way to trigger IOExceptions during the response body so use an interceptor.
    OkHttpClient client = //
    new OkHttpClient.Builder().addInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.Response response = chain.proceed(chain.request());
            ResponseBody body = response.body();
            BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) {

                @Override
                public long read(Buffer sink, long byteCount) throws IOException {
                    throw new IOException("cause");
                }
            });
            body = ResponseBody.create(body.contentType(), body.contentLength(), source);
            return response.newBuilder().body(body).build();
        }
    }).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client).addConverterFactory(new ToStringConverterFactory() {

        @Override
        public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
            return new Converter<ResponseBody, String>() {

                @Override
                public String convert(ResponseBody value) throws IOException {
                    try {
                        return value.string();
                    } catch (IOException e) {
                        // Some serialization libraries mask transport problems in runtime exceptions. Bad!
                        throw new RuntimeException("wrapper", e);
                    }
                }
            };
        }
    }).build();
    Service example = retrofit.create(Service.class);
    server.enqueue(new MockResponse().setBody("Hi"));
    Call<String> call = example.getString();
    try {
        call.execute();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage("cause");
    }
}
Also used : Buffer(okio.Buffer) MockResponse(okhttp3.mockwebserver.MockResponse) OkHttpClient(okhttp3.OkHttpClient) ForwardingSource(okio.ForwardingSource) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) Type(java.lang.reflect.Type) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) Interceptor(okhttp3.Interceptor) BufferedSource(okio.BufferedSource) Test(org.junit.Test)

Example 95 with Retrofit

use of retrofit2.Retrofit in project retrofit by square.

the class CallTest method conversionProblemOutgoingAsync.

@Test
public void conversionProblemOutgoingAsync() throws InterruptedException {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).addConverterFactory(new ToStringConverterFactory() {

        @Override
        public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
            return new Converter<String, RequestBody>() {

                @Override
                public RequestBody convert(String value) throws IOException {
                    throw new UnsupportedOperationException("I am broken!");
                }
            };
        }
    }).build();
    Service example = retrofit.create(Service.class);
    final AtomicReference<Throwable> failureRef = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    example.postString("Hi").enqueue(new Callback<String>() {

        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            throw new AssertionError();
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            failureRef.set(t);
            latch.countDown();
        }
    });
    assertTrue(latch.await(10, SECONDS));
    assertThat(failureRef.get()).isInstanceOf(UnsupportedOperationException.class).hasMessage("I am broken!");
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Type(java.lang.reflect.Type) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) RequestBody(okhttp3.RequestBody) Test(org.junit.Test)

Aggregations

Retrofit (retrofit2.Retrofit)76 Test (org.junit.Test)42 ToStringConverterFactory (retrofit2.helpers.ToStringConverterFactory)35 Before (org.junit.Before)34 MockResponse (okhttp3.mockwebserver.MockResponse)30 Type (java.lang.reflect.Type)17 OkHttpClient (okhttp3.OkHttpClient)16 ResponseBody (okhttp3.ResponseBody)16 IOException (java.io.IOException)13 ParameterizedType (java.lang.reflect.ParameterizedType)13 MediaType (okhttp3.MediaType)13 NonMatchingConverterFactory (retrofit2.helpers.NonMatchingConverterFactory)13 CountDownLatch (java.util.concurrent.CountDownLatch)12 AtomicReference (java.util.concurrent.atomic.AtomicReference)12 NonMatchingCallAdapterFactory (retrofit2.helpers.NonMatchingCallAdapterFactory)11 GsonBuilder (com.google.gson.GsonBuilder)10 DelegatingCallAdapterFactory (retrofit2.helpers.DelegatingCallAdapterFactory)10 Annotation (java.lang.annotation.Annotation)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 Request (okhttp3.Request)7