Retrofit – probably the most popular networking client in Android development. Basically it allows to create HTTP client in an interface – you just add annotation with HTTP method, relative or absolute path and proper request is constructed. Retrofit does not generate code in compile time – it creates implementations in runtime.
The method invocation:
remoteApi.searchByPhrase("asd")
Will create GET request to:
http://some.host/api/data?search=asd
Now we will try to come up with a way to check if proper requests are constructed.
Basic test case
We will consider the following Retrofit interface with given configuration:
How could we actually perform some assertions on that? Was actually GET method used? Was search phrase included in query?
While we are using retrofit2.Call<T> we have Call.request() method available directly and we can perform assertions on Request object:
Test case with non-standard call adapter factory
In my opinion the power of Retrofit comes from call and converter adapter factories – instead of relying on built-in types (such as retrofit2.Call) you can add RxJava call adapter and framework would find a way to convert Call<T> into rx Single<T>. Unfortunately we won’t have direct access to Call.request() method then!
To handle this case and have request to perform assertions on I came up with the following approach:
Use OkHttp MockWebServer to record incoming requests
Wrap system under test invocation with RemoteApi as lambda parameter and RecordedRequest as return type
Perform assertions on RecordedRequest
I highly encourage you to explore more methods and properties available in RecorderRequest – you may find there more things that may be useful in your test.
Now we have a way to perform assertions on request that was recorded in MockWebServer – with this approach we can design even more complex integration test suites.
This repository contains examples of basic unit tests written in Kotlin. In specific directories you can find gradle buildscript with needed dependencies and configuration, simple…
Your view model class usually has several functionalities. It somehow fetches data, it optionally maps your data entities to displayable entities, handles clicks and performs…
Everyone knows the situations when we have to check our system for various input. A good example would be a login/password validation performed both on…