5

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!

Dillon
  • 364
  • 5
  • 18
  • So right now my intent is to create another field of `Foo` and another constructor of `SomeContentProvider` that takes in a `Foo` just for testing purpose, after inject, if that field does exist, replace the injected `Foo` – Dillon Dec 14 '17 at 22:04

2 Answers2

1

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?

Dillon
  • 364
  • 5
  • 18
0

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

  • Im not sure if you understood my question correctly. Names qualifier would not be needed in my case. – Dillon Dec 14 '17 at 18:58