Skip to content

Instantly share code, notes, and snippets.

@riggaroo
Last active May 1, 2021 17:52
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save riggaroo/a33e1108cf6c2141e2f0 to your computer and use it in GitHub Desktop.
Save riggaroo/a33e1108cf6c2141e2f0 to your computer and use it in GitHub Desktop.
Mocking API Responses using a Retrofit Client in Android
public class RestServiceMockUtils {
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile(Context context, String filePath) throws Exception {
final InputStream stream = context.getResources().getAssets().open(filePath);
String ret = convertStreamToString(stream);
//Make sure you close all streams.
stream.close();
return ret;
}
public static RetrofitMockClient getClient(Context context, final int httpStatusCode, String reason, String responseFileName) throws Exception {
return new RetrofitMockClient(httpStatusCode, reason, getStringFromFile(context, responseFileName));
}
}
{
"error": {
"code": 401,
"message": "Unauthorized"
}
}
public class QuoteOfTheDayServiceTests extends InstrumentationTestCase {
public static final TAG = "QODServiceTest";
public static final String BASE_API_URL = "http://api.theysaidso.com/";
@SmallTest
public void testAuthoriseFailsForIncorrectSessionId() throws Exception {
String jsonResponseFileName = "quote_401_unauthorised.json";
int expectedHttpResponse = 401;
String reason = "Unauthorised";
//Create RetrofitMockClient with the expected JSON response and code.
RetrofitMockClient retrofitMockClient = RestServiceMockUtils.getClient(getInstrumentation().getContext(), expectedHttpResponse, reason, jsonResponseFileName);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_API_URL)
.setClient(retrofitMockClient)
.setConverter(new JacksonConverter())
.setErrorHandler(new RetrofitErrorHandler())
.build();
RestService restServiceClient = restAdapter.create(RestService.class);
//Run test code - you can test anything you want to here, test the correct response, the way the UI displays for certain mock JSON.
String incorrectApiKey = "incorrectApiKey";
try {
String quote = restServiceClient.getQuoteOfTheDay(incorrectApiKey);
Assert.fail("Should have thrown unauthorised exception");
} catch (UnauthorizedException unauthorised) {
Log.d(TAG, "Successfully caught unauthorised exception when incorrect API key was passed");
}
}
}
public class RetrofitMockClient implements Client {
private String jsonResponse;
private int statusCode = 200;
private String reason;
private static final String MIME_TYPE = "application/json";
public RetrofitMockClient(int statusCode, String reason, String jsonResponse) {
this.statusCode = statusCode;
this.reason = reason;
this.jsonResponse = jsonResponse;
}
@Override
public Response execute(Request request) throws IOException {
return createDummyJsonResponse(request.getUrl(), statusCode, reason, jsonResponse);
}
private Response createDummyJsonResponse(String url, int responseCode, String reason, String json) {
return new Response(url, responseCode, reason, Collections.EMPTY_LIST,
new TypedByteArray(MIME_TYPE, json.getBytes()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment