android - Injecting mock Retrofit API service instance into ActivityInstrumentTestCase2 -
i'd write functional tests espresso activity using mock retrofit api service instance created mockrestadapter (https://github.com/square/retrofit/blob/master/retrofit-mock/src/main/java/retrofit/mockrestadapter.java).
this bit tricky though, can't ever inject dependencies via activity's constructor.
currently, single retrofit api service instance lives in application object, , create reference in each of activities' oncreate()
methods.
how can swap in mock retrofit api service? perhaps dagger answer?
yes, dagger answer. on how accomplish this, recommend @ jake wharton's u2020 @ github. in nutshell, provide different api implementations production , debug flavors. or, have separate flavor integration tests.
another way solve without dagger (adding back upwards quite undertaking ongoing project), have flavor integration tests. e.g. have release
, debug
, mock
flavors.
then have different application
class set in android manifest mock
flavor - implementation uses mock adapter. core thought here can override or augment main androidmanifest in flavors.
that'd this:
project structure
app/ src/ main/ androidmanifest.xml - activities, services, permissions - stuff goes here java/.../myapplication.java mock/ androidmanifest.xml - illustration below java/.../mockapplication.java debug/ - not relevant illustration release/ - not relevant illustration
main/androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.example.android" > <!-- permissions etc --> <application android:name=".myapplication" ... > <!-- activities, services etc --> </application> </manifest>
mock/androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:name=".mockapplication"/> </manifest>
application.java
class="lang-java prettyprint-override">public class myapplication extends application { @override public void oncreate(bundle savedstate) { myapi api = createapiadapter(); } protected myapi createapiadapter() { // create regular retrofit adapter } }
mockapplication.java
class="lang-java prettyprint-override">public class mockapplication extends myapplication { @override protected myapi createapiadapter() { // create mock retrofit adapter } }
build.gradle
android { // ... buildtypes { mock { applicationidsuffix '.mock' versionnamesuffix '-mock' debuggable true } debug { applicationidsuffix '.dev' versionnamesuffix '-dev' debuggable true } release { signingconfig signingconfigs.release } } }
android functional-testing retrofit dagger android-espresso
No comments:
Post a Comment