dagger 1

fb-android-dagger 1.0.6 released

This release includes two new injecting base classes:

  • InjectingAppWidgetProvider
  • InjectingActionBarActivity (suggested by Tyler Chesley)

In addition, InjectingApplication was enhanced with a new addSeedModules() method to facilitate unit testing with test-method-specific dagger modules. See Initialize your Android component’s dagger object graph on a per-method basis in your Robolectric tests for a detailed explanation of how to use this feature.

Finally, InjectingServiceModule's provideApplicationContext() provider method was replaced with provideServiceContext, which seems to make more sense in that, uh... context.

Initialize your Android component's dagger object graph on a per-method basis in your Robolectric tests

{note: this blog entry is about dagger 1}

When writing unit tests for Android applications, my go-to tools are Robolectric, dagger, and Mockito.  The combination covers a lot of ground in terms of providing "stand ins" for a lot of Android system functionality and factoring out dependencies from the objects under test by injecting mocks into them.  In my production code, my components derive from helper classes in my fb-android-dagger library, which takes care of creating object graphs and self-injecting those components during their initialization logic. fb-android-dagger's component base classes allows subclasses (including test classes) to participate in establishing the dagger modules to use when creating the object graph.  Thus, a production component might use a module which provides dependency X, while a test component could subclass from the production component and tack on a test module which overrides the production module and provides a mock X instead.

This all works pretty well, but it has a limitation -- the opportunity to override production modules with test modules exists only at the time that the component's initialization method runs.  In practice, this means that if the different test methods in a test class want different mocks to be injected into the component under test, they need to employ some technique to ensure that (1) the set of modules used to create the object graph is established by code which is specific to the test method (which rules out the @Before method, since it is method-independent), and (2) the component under test doesn't get initialized until after (1).

My usual approach to this problem is to defer initialization (which includes object graph generation and injection) of the component under test until inside the test method (as opposed to the @Before method).  In the test method, I first set up my mocks (which are fields of the test class) to provide the desired behavior, then initialize the component under test.  For the test subclass of my component, I override getModules() to supply a module (with overrides=true) that has provider methods which provide the mocks configured in the test method.  Note that this overriding module class must be non-static to have access to the mocks in the test class.

In the following example, assume that MyBroadcastReceiver is the class of the object under test, and it extends InjectingBroadcastReceiver from fb-android-dagger.


@RunWith(RobolectricTestRunner.class)
public class MyTest {
    private X mockX = Mockito.mock(X.class);
 
    BroadcastReceiver testReceiver = new TestMyBroadcastReceiver();
 
    @Test
    public void onReceive_doesSomethingWhenXIsEnabled() {
        // for this test, I want to simulate an "enabled" X
        Mockito.when(mockX.getEnabled()).thenReturn(true);
 
        // onReceive will build the object graph and inject itself using a provider
        // which returns mockX.
        testReceiver.onReceive(...);
 
        // ... verification logic...
    }
 
    @Test
    public void someMethod_doesSomethingDifferentWhenXIsDisabled() {
        // for this test, I want to simulate a "disabled" X
        Mockito.when(mockX.getEnabled()).thenReturn(true);
 
        // etc.
    }
 
    private class TestMyBroadcastReceiver extends MyBroadcastReceiver {
        @Override
        protected List<Object> getModules() {
            List<Object> result = super.getModules();
            result.add(new MockXModule());
            return result;
        }          
    }
 
    @Module(injects=MyBroadcastReceiver, overrides=true)
    private class MockXModule {
        @Provides
        public X provideX() {
            return mockX;
        }
    }
}

However, this approach doesn't work if you want to tweak the Application-scope object graph on a per-method basis, because Robolectric creates and initializes (and hence injects) the Application object for you implicitly before your test method runs.  Even if you have a test application class that overrides getModules() and adds modules with provider methods that leverage the state of the test object (i.e. using the technique above), it won't work, because getModules() will get called before the test method runs, and therefore the test method will have no opportunity to configure the test object's state prior to injection of the application object.

Robolectric does provide hooks in the form of the TestLifecycleApplication interface, whose beforeTest, prepareTest, and afterTest methods you can implement in your test application class, but they aren't helpful in this case, since they all run after your test application's onCreate() method has already been called (and thus its object graph has already been created and used to inject it).

One workaround to this problem would be to use different test application classes for different methods, using Robolectric 2.4's @Config(application=...) annotation on a per-method basis.  With this approach, you'd need your different test application classes to specify different modules in their getModules() implementations, each hardcoded to provide the desired mock behavior for the corresponding test method.  Note: here we're assuming that MyBroadcastReceiver's dependency on X is satisfied from the Application-scope object graph.


@Test 
@Config(application=TestMyBroadcastReceiverWithXEnabled.class) 
public void onReceive_doesSomethingWhenXIsEnabled() { ... }

@Test 
@Config(application=TestMyBroadcastReceiverWithXDisabled.class) 
public void onReceive_doesSomethingDifferentWhenXIsDisabled() { ... }

private class TestMyBroadcastReceiverWithXEnabled extends MyBroadcastReceiver { 
    @Override protected List<Object> getModules() { 
    List<Object> result = super.getModules();
    result.add(new MockXEnabledModule()); 
    return result; 
    } 
}

private class TestMyBroadcastReceiverWithXDisabled extends MyBroadcastReceiver { 
    @Override protected List<Object> getModules() { 
        List<Object> result = super.getModules(); 
        result.add(new MockXDisabledModule()); 
        return result; 
    } 
}

@Module(injects=MyBroadcastReceiver, overrides=true) 
private class MockXEnabledModule { 
    @Provides public X provideX() { 
        X mockX = mock(X.class); 
        when(mockX.isEnabled()).thenReturn(true); 
        return mockX; 
    } 
}

@Module(injects=MyBroadcastReceiver, overrides=true) 
private class MockXDisabledModule { 
    @Provides public X provideX() {
        X mockX = mock(X.class);
        when(mockX.isEnabled()).thenReturn(false); 
        return mockX; 
    }
}

 

That can get a little unwieldy when you start having combinations of method-specific modules, since each combination would need a different test application subclass.  To avoid that kind of proliferation, I've implemented a subclass of RobolectricTestRunner called InjectingRobolectricTestRunner, which looks for annotations like


@Test 
@With(appModules={MockXEnabledModule.class}) 
public void onReceive_doesSomethingWhenXIsEnabled() { ... } 

and takes care of seeding the annotation-specified modules into the Application object prior to its onCreate() method being called.  This required two small enhancements to InjectingApplication in fb-android-dagger: (a) a new setter method by which the InjectingRobolectricTestRunner can assign the seed modules, and (b) an update to its getModules() method, to add the seed modules into the list it returns.

In some cases, this approach may eliminate the need for test application subclasses altogether, but it works with them just as well -- the annotations establish the method-specific modules, and the test application class' getModules() method tacks on any others that are not method-specific.  As with the first approach described above, note that the test-specific modules must be hardcoded to exhibit the desired method-specific behavior. Here's the code for InjectingRobolectricTestRunner:


public class InjectingRobolectricTestRunner extends RobolectricTestRunner {
    public InjectingRobolectricTestRunner(Class testClass) throws InitializationError { 
        super(testClass); 
    }

    @Override protected Class getTestLifecycleClass() { 
        return InjectingTestLifecycle.class; 
    }

    public static class InjectingTestLifecycle extends DefaultTestLifecycle {

        @Override public Application createApplication(Method method, AndroidManifest appManifest, Config config) { 
            InjectingApplication injectingApplication = (InjectingApplication) super.createApplication(method, appManifest, config);

            List<Object> seedModules = new ArrayList<>();

            if (method.isAnnotationPresent(With.class)) { 
                With with = method.getAnnotation(With.class); 
                for (Class<?> clazz : with.appModules()) { 
                    try { 
                        seedModules.add(clazz.newInstance()); 
                    } catch (InstantiationException e) { 
                        e.printStackTrace(); 
                    } catch (IllegalAccessException e) { 
                        e.printStackTrace(); 
                    } 
                }
            }

            injectingApplication.addSeedModules(seedModules); 
            return injectingApplication; 
        }
    }

    @Qualifier 
    @Target(METHOD) 
    @Documented 
    @Retention(RUNTIME) 
    public @interface With { 
        Class<?>[] appModules(); 
    } 
}


tip: to bind dagger singletons to a particular object graph scope, use injects=

 

{note: this blog entry is about dagger 1}

If you want singleton semantics for injected objects, dagger offers two approaches - you can implement a @Singleton-annotated provider method, or you can implement an @Inject-annotated constructor in a @Singleton-annotated class. The latter approach is obviously a little more concise, but it raises one issue, which is that in an application with multiple object graphs, some of which extend others (e.g. an Activity-scope graph that extends an Application-scope graph), dagger will maintain singletons of those @Singleton-annotated classes in each object graph that is requested to inject one.  So if you've got a @Singleton-annotated Foo class, you could end up with one Foo object shared by objects that are injected via the Activity-scope graph, and another Foo object shared by objects injected via the Application-scope graph.

There are two ways to avoid this.  Let's assume you want only one Foo instance and you want it to be bound to the Application-scope graph.  In your Application module declaration, you could (1) add a @Singleton-annotated provider method for Foo, or (2) include Foo.class in the "injects=" part of your @Module annotation.  When I first read about this, I found it a little confusing, as I thought the "injects=" list was just for enumerating the classes that the module injects into, but some experimentation confirmed that specifying classes to inject has the effect of binding their @Inject-annotated constructor to that module (essentially creating an implicit provider), and thus to the object graph created from it.

Introducing fb-android-dagger - a helper lib for using dagger with Android

A while back, Square released a new dependency injection framework called dagger, emphasizing simplicity and performance (via compile-time code generation rather than runtime reflection). Dagger actually has no Android dependencies and thus can be used in other contexts, but it has gained traction among Android developers. As I started working with it, it quickly became clear that it would be handy to have a set of reusable base classes that integrate dagger with the standard Android components like Application, Service, BroadcastReceiver, Activity, and Fragment. And so, fb-android-dagger was born. I open sourced it about a year ago, and a few people seem to be using it, so it's probably (past) time I introduced it.

Creating object graphs

I'll skip over the dagger basics, as they're explained well on Square's dagger page, but I'll note that a useful implementation pattern that quickly emerged is to have a component base class do the ObjectGraph initialization and injection of "this" in its first lifecycle method (e.g. Activity.onCreate()). To initialize the graph, that code needs the set of applicable dagger modules, so the base class defines a getModules() method which it expects subclasses to override by supplying the modules they want to contribute to the graph.

Here's a typical subclass implementation of getModules():


public class MyActivity extends InjectingActivity {

// ...

    @Override protected List<Object> getModules() {
        List<Object>
        modules = super.getModules();
        modules.add(new MyModule());
        return modules; 
    } 
} 

s you can see, the idea is for the module list to be built cooperatively via the getModule() overrides in the chain of classes deriving from the injecting base class. Each class' getModules() method first gets its superclass' module list, add its own modules to the list and returns the combined list.

fb-android dagger's set of component base classes each implement this mechanism, in a lifecycle method appropriate to the component:

  • InjectingApplication (onCreate)
  • InjectingBroadcastReceiver (onReceive)
  • InjectingService (onCreate)
  • InjectingActivity (onCreate)
  • InjectingFragmentActivity (onCreate)
  • InjectingPreferenceActivity (onCreate)
  • InjectingFragment (onAttach)
  • InjectingListFragment (onAttach)
  • InjectingDialogFragment (onAttach)

In addition, the graphs that fb-android-dagger creates are scoped to their associated components, so the graph created by MyActivityOne is distinct from the graph created for MyActivityTwo. However, it does reuse and extend graphs created by other components, working "outward" from the Application graph:

  • an Application-scope graph is created by InjectingApplication
  • InjectingBroadcastReceiver creates a BroadcastReceiver-scoped graph that extends the Application-scope graph.
  • InjectingServiceReciever creates a Service-scoped graph that extends the Application-scoped graph
  • InjectingActivity, InjectingFragmentActivity, and InjectingPreferenceActivity create Activity-scoped graphs that extend the Application-scoped graph.
  • InjectingFragment, InjectingDialogFragment, and InjectingListFragment create Fragment-scoped graphs that extend their associated Activity's graph.

Helper modules

fb-android-dagger also provides a set of dagger modules and qualifier annotations to facilitate injection of objects relevant to their component type.

For example, a class injected by an Activity-scope graph could get the Activity's context and the Application context injected like so:


class Foo1 { 
    @Inject @Application Context appContext;
    @Inject @Activity Context activityContext; // ... 
}

A class can also access relevant components themselves, directly:


class Bar { 
    @Inject Application theApp;
    @Inject Activity myActivity; 
    @Inject Fragment myFragment; // ... 
}

Feel free to give a try!

Source is on Github

Maven users can download from Maven Central:


<dependency> 
	<groupId>com.fizz-buzz</groupId>
    <artifactId>fb-android-dagger</artifactId>
    <version>1.0.3</version> 
</dependency>