Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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