Last active
June 24, 2022 16:55
-
-
Save Aesthetikx/6d80d2cf63c31a211e00 to your computer and use it in GitHub Desktop.
Testing Retrofit Callback style APIs with Robolectric and CountdownLatches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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()); | |
} | |
} |
Yeah, neat example!
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
Thanks a lot, It was very useful