Skip to content

Instantly share code, notes, and snippets.

@Axxiss
Last active June 2, 2016 18:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Axxiss/7143760 to your computer and use it in GitHub Desktop.
Save Axxiss/7143760 to your computer and use it in GitHub Desktop.
Testing AsyncHttpClient with Robolectric
public class AsyncTester {
protected static final int HTTP_OK = 200;
protected ApiCallback mCallback;
private ProtocolVersion mHttpVersion;
protected AsyncHttpClient mHttpClient = new AsyncHttpClient();
@Before
public void setUp() {
BlockingQueue<Runnable> queue = new SynchronousQueue<Runnable>();
TestExecutorService pool = new TestExecutorService(10, 10, 10, TimeUnit.MILLISECONDS, queue);
mHttpVersion = new ProtocolVersion("HTTP", 1, 1);
mHttpClient.setThreadPool(pool);
}
/**
* Mock a pending response.
*
* @param url
* @param response the response to return, when the request is done.
*/
protected void addPendingResponse(String url, String response) {
HttpResponse successResponse = new BasicHttpResponse(mHttpVersion, 200, response);
Robolectric.addHttpResponseRule(absoluteUrl, successResponse);
}
/**
* Mock a pending response. {@code ApiMock.mockSuccess()} is returned as a
* response.
*
* @param url
*/
protected void addPendingResponse(String url) {
addPendingResponse(url, ApiMock.mockSuccess());
}
}
public class TestExecutorService extends ThreadPoolExecutor {
public TestExecutorService(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
@Override
public Future<?> submit(Runnable runnable) {
FutureTask futureTask = new FutureTask(runnable, null);
futureTask.run();
return futureTask;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment