Android functional testing with Dagger

前端 未结 3 2268
借酒劲吻你
借酒劲吻你 2021-02-13 21:52

I’m trying to test an Activity with Mockito & Dagger. I have been able to inject dependencies to Activity in my application but when testing the Activity, I have not been a

3条回答
  •  青春惊慌失措
    2021-02-13 22:07

    I did some more experimenting and found out that Dagger is not able to create activity correctly when it is injected to test. In the new version of test, testDoSomethingCalledOnEngine passes but onCreate is not called on the MainActivity. The second test, testDoSomethingUI fails and there are actually two instances of MainActivity, onCreate gets called to the other instance (created by ActivityInstrumentationTestCase2 I quess) but not to the other. Maybe the developers at Square only thought about testing Activites with Robolectric instead of Android instrumentation test?

    public class MainActivityTest extends
        ActivityInstrumentationTestCase2 {
    
    @Inject Engine engineMock;
    @Inject MainActivity mActivity;
    
    public MainActivityTest() {
        super(MainActivity.class);
    }
    
    @Override
    protected void setUp() throws Exception {
        super.setUp();
    
        // Inject engineMock to test & Activity under test
        ObjectGraph.create(new TestModule()).inject(this);
    }
    
    
     @Module(
     includes = MainModule.class,
     entryPoints = MainActivityTest.class,
     overrides = true
     )
    
    static class TestModule {
        @Provides
        @Singleton
        Engine provideEngine() {
            return mock(Engine.class);
        }
    }
    
    public void testDoSomethingCalledOnEngine() {
        when(engineMock.isLoggedIn()).thenReturn(true);
        mActivity.onSomethingHappened();
        verify(engineMock).doSomething();
    }
    
    @UiThreadTest
    public void testDoSomethingUI() {
        when(engineMock.isLoggedIn()).thenReturn(true);
        mActivity.onSomethingHappened();
        Button btn = (Button) mActivity.findViewById(R.id.logoutButton);
        String btnText = btn.getText().toString(); 
        assertTrue(btnText.equals("Log out"));  
    }
    

    }

提交回复
热议问题