Skip to content

Instantly share code, notes, and snippets.

@Aesthetikx
Last active June 24, 2022 16:55
Show Gist options
  • Save Aesthetikx/6d80d2cf63c31a211e00 to your computer and use it in GitHub Desktop.
Save Aesthetikx/6d80d2cf63c31a211e00 to your computer and use it in GitHub Desktop.
Testing Retrofit Callback style APIs with Robolectric and CountdownLatches
// WidgetApi.java
public interface WidgetApi {
@GET("/widget/{:id}")
void getWidget(@Path("id") int id, Callback<Widget> callback);
}
// MockRetrofitClient.java
public class MockRetrofitClient implements Client {
private int statusCode = 200;
private String responseBody = "{}";
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public void setResponseBody(String responseBody) {
this.responseBody = responseBody;
}
@Override
public Response execute(Request request) throws IOException {
return new Response(request.getUrl(),
statusCode,
responseBody,
Collections.EMPTY_LIST,
new TypedByteArray("application/json", responseBody.getBytes()));
}
}
// WidgetApiTest.java
@RunWith(RobolectricGradleTestRunner.class)
public class WidgetApiTest {
private WidgetApi api;
private MockRetrofitClient client;
private Widget widget;
@Before
public void setUp() {
client = new MockRetrofitClient();
Executor executor = Executors.newSingleThreadExecutor();
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint("https://mock.com")
.setClient(client)
.setExecutors(executor, executor)
.build();
api = adapter.create(WidgetApi.class);
}
private String loadFixture(String relativePath) throws IOException {
String path = "src/test/fixtures/" + relativePath;
return FileUtils.readFileToString(new File(path));
}
@Test
public void testGetWidget() throws Exception {
client.setResponseBody(loadFixture("/api/widgets/widget-1.json"));
final CountDownLatch latch = new CountDownLatch(1);
api.getWidget(1, new Callback<Widget>() {
@Override
public void success(Widget widget, Response response) {
this.widget = widget;
latch.countDown();
}
@Override
public void failure(RetrofitError error) {
this.widget = null;
latch.countDown();
}
});
latch.await();
assertEquals("test-widget-name", widget.getName());
}
}
@hshahdoost
Copy link

Thanks a lot, It was very useful

@mgj
Copy link

mgj commented May 2, 2018

Yeah, neat example!

@mochadwi
Copy link

thanks a lot, this is a very nice example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment