@Test public void testAnswer() throws IOException { interceptor.addRule() .get() .pathMatches(Pattern.compile("/aPath/(\\w+)")) .anyTimes() .answer(new RuleAnswer() { @Override public Response.Builder respond(Request request) { return new Response.Builder() .code(200) .body(ResponseBody.create(null, request.url().encodedPath())); } }); String[] paths = new String[]{"/aPath/aaa", "/aPath/bbb", "/aPath/ccc"}; for (String expectedBody : paths) { HttpUrl url = HttpUrl.parse(TEST_URL).newBuilder().encodedPath(expectedBody).build(); String body = client.newCall(new Request.Builder() .url(url) .get() .build()) .execute() .body() .string(); assertEquals(expectedBody, body); } }
@Test public void testCustomResponse() throws IOException { final String json = "{\"succeed\":true}"; interceptor.behavior(Behavior.SEQUENTIAL).addRule() .get().or().post().or().put() .respond(json, MEDIATYPE_JSON); assertEquals(json, client.newCall(new Request.Builder() .url(TEST_URL) .get() .build()) .execute() .body() .string()); }
public Response.Builder respond(long contentLength, @NonNull InputStream body) { return respond(contentLength, body, MEDIATYPE_RAW_DATA); }
public Response.Builder respond(@NonNull InputStream body, @NonNull MediaType mediaType) { return respond(-1, body, mediaType); }
public Response.Builder respond(@NonNull byte[] body, @NonNull MediaType mediaType) { return respond(ResponseBody.create(mediaType, body)); }
public Response.Builder respond(@NonNull byte[] body) { return respond(body, MEDIATYPE_RAW_DATA); }
@Test public void testGetMultipleTimes() throws IOException { interceptor.addRule() .get(TEST_URL) .anyTimes() .respond(TEST_RESPONSE); String first = null; for (int i = 0; i < 10; i++) { String actual = client.newCall(new Request.Builder().url(TEST_URL).get().build()) .execute().body().string(); if (first == null) { first = actual; } else { assertEquals(first, actual); } } }
public Response.Builder respond(@NonNull InputStream body) { return respond(-1, body); }
public Response.Builder respond(@NonNull String body) { return respond(body, MEDIATYPE_TEXT); }
public Response.Builder respond(int code) { return respond(code, (ResponseBody) null); }
public Response.Builder respond(@NonNull String body, @NonNull MediaType mediaType) { return respond(ResponseBody.create(mediaType, body)); }
public Builder pathMatches(Pattern pattern) { matches(new PathMatcher(pattern)); return this; }
public Builder pathStarts(String prefix) { pathMatches(prefix(prefix)); return this; }
public Builder urlMatches(Pattern pattern) { matches(new URLMatcher(pattern)); return this; }
public Builder header(String header, String value) { headerMatches(header, exact(value)); return this; }
public Builder pathEnds(String suffix) { pathMatches(suffix(suffix)); return this; }
public Builder paramMatches(String param, Pattern pattern) { matches(new QueryParamMatcher(param, pattern)); return this; }