Dillon
Dillon

Reputation: 364

Dagger Field Injection Testing

I am using Dagger 2 and have a few issues with generate singleton providers in the module when implementing tests for my class.

class SomeContentProvider extends ContentProvider {

    // this should be normal foo if run by application, 
    // or mocked foo if run by tests
    @Inject Foo foo;

    public Provider() {
        Component.getComponent().inject(this);
    }
}

@Module
class ProviderModule {
    @Singleton
    @Provides
    Foo providesFoo() {
        returns new Foo();
    }
}

@Module
class ProviderTestModule {
    @Singleton
    @Provides
    Foo providesFoo() {
        returns Mockito.mock(Foo.class);
    }
}


public class SomeContentProviderTests extends InstrumentationTestCase {

    @Inject Foo foo; // this should be mocked Foo

    @Override
    public void setUp() throws Exception {
        super.setUp();

        MockitoAnnotations.initMocks(this);

        Component.getTestComponent().inject(this);
    }

    public void test1() {
        // needs new instance of Foo when test1 is run from SomeContentProvider
    }

    public void test2() {
        // needs another new instance of Foo when test2 is run from SomeContentProvider
    }
}

So I have 2 questions.

  1. I cannot use constructor injection as ContentProvider has a default constructor. How does SomeContentProvider get the Foo from the the test module?

  2. In test1 and test2, how do I ensure that a new instance of Foo is created when each test is being run?

Thanks!

Upvotes: 5

Views: 4876

Answers (2)

Dillon
Dillon

Reputation: 364

I found this post especially useful for me. Though the particular problem I am have is much more convoluted - but I had used the same idea to mock the module's provider.

How do you override a module/dependency in a unit test with Dagger 2.0?

Upvotes: 1

Wellington Costa
Wellington Costa

Reputation: 153

You should use the @Named annotation for identify which dependency you want to inject if you have more than one dependency of same type.

See docs for more details: https://google.github.io/dagger/users-guide#qualifiers

Upvotes: 0

Related Questions