Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vgaidarji/609719adfeefd96e6e55 to your computer and use it in GitHub Desktop.
Save vgaidarji/609719adfeefd96e6e55 to your computer and use it in GitHub Desktop.
// 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());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment