Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Injected Constructors in Dagger 2

I have an activity with a dependency:

public class MyActivity extends AppCompatActivity {

    @Inject Dependency;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // inject
    }

 }

public class Dependency {

    @Inject
    public Dependency() {
        //..
    }

 }

Since Dependency has an injected constructor, Dagger2 doesn't require a module to know how to instantiate it, which is super convenient.

My question is: For testing purposes, do I have to have an explicit module that provides Dependency in order to be able to mock it and provide a mock version of Dependency? or is there a way to mock Dependency without it?

like image 661
Itai Hanski Avatar asked Sep 01 '26 11:09

Itai Hanski


1 Answers

I found a way without creating an explicit Module. Here's how I did it using Robolectric and Mockito:

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class MyActivityTest {

    @Mock AppComponent mAppComponent;
    @Mock private Dependency mDependency;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

        // ***
        // use the mock AppComponent to perform injections
        // ***

        doAnswer(new Answer() {
            public Object answer(InvocationOnMock invocation) {
                ((MyActivity) invocation.getArguments()[0]).mDependecy = mDependecy;
                return null;
            }
        }).when(mAppComponent).inject(any(MyActivity.class));
    }
}
like image 98
Itai Hanski Avatar answered Sep 03 '26 01:09

Itai Hanski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!