I am trying to test the set of changes that I make for my Android service ( android.app.Service ). I use Dagger and Robolectric, and I need to replace the fields entered in the class, in some services, reduce the scope of inspection ... make (a little) more "unit".
So, the short version ...
I embed Providers.of (Guice syntax ...) in my android.app.Service . How to replace them with MockProviders during unit test?
Longer version ...
Here's what the corresponding service code looks like:
@Inject SpotService spotService; @Inject Provider<SynchroniseTidePosition> syncTidePosition; @Inject Provider<SynchroniseSwellDataTask> syncBuoyData; @Inject Provider<SynchroniseConditionsTask> syncConditionsData; @Inject SpotRatingCalculator spotRatingCalculator; @Inject LocalBroadcastManager localBroadcastManager; @Inject NotificationManager notificationManager; @Override public void onCreate() { super.onCreate(); inject(this); ...
So, during normal operation, calling startService(intent) allows the service to insert it with dependencies during onCreate , and we are all good.
In my test, I want to replace the nested Provider get() calls with Mockito mocks. I tried to run a dagger test example and created a test module that looks like this:
@Module(includes = OceanLifeModule.class, injects = {TestSynchronisationServiceNotifications.class}, overrides = true) static class TestSynchronisationServiceNotificationsModule { @Provides LocalBroadcastManager provideLocalBroadcastManager() { return LocalBroadcastManager.getInstance(Robolectric.application); } @Provides NotificationManager providesNotificationManager() { return (NotificationManager) Robolectric.application.getSystemService(Context.NOTIFICATION_SERVICE); } @Provides SpotService provideSpotService() { return mock(SpotService.class); } @Provides SpotRatingCalculator provideSpotRatingCalculator() { return mock(SpotRatingCalculator.class); } @Provides SynchroniseTidePosition provideSyncTidePosition() { return mock(SynchroniseTidePosition.class); } @Provides SynchroniseConditionsTask provideSyncConditionsTask() { return mock(SynchroniseConditionsTask.class); } @Provides SynchroniseSwellDataTask provideSyncSwellDataTask() { return mock(SynchroniseSwellDataTask.class); } }
I expect that when my actual service code calls the get() provider, I get the Mockito mocks back (these are the midges that my test module is @Provides).
This is not happening. What happened to the approach I'm heading here for?
source share