Android Testing with Robolectric and Dagger

前端 未结 3 1004
一生所求
一生所求 2021-01-24 23:33

I am trying to write an Android application using Dagger. Trying to follow the TDD approach, I started writing a test for my First activity. For writing tests I am using Robole

3条回答
  •  无人及你
    2021-01-24 23:58

    Here's what you can do. Create two different modules in the test class. One which provides Internet Connection as true and another as Internet Connection as False. Once you have the two different module's setup inject them in the individual test class rather than the setUp of the Test Class. So:

    @Module(
        includes = AppModule.class,
        injects = {SplashScreenActivityTest.class,
                SplashScreenActivity.class},
        overrides = true
    )
    public class GeneralUtilsModuleNoInternetConnection
    {
    public GeneralUtilsModuleNoInternetConnection() {
    }
    
    @Provides
    @Singleton
    GeneralUtils provideGeneralUtils() {
    
        GeneralUtils mockGeneralUtils = Mockito.mock(GeneralUtils.class);
    
        when(mockGeneralUtils.isInternetConnection()).thenReturn(false);
    
        return mockGeneralUtils;
    }
    }
    

    The second module:

    @Module(
        includes = AppModule.class,
        injects = {SplashScreenActivityTest.class,
                SplashScreenActivity.class},
        overrides = true
    )
    public class GeneralUtilsModuleWithInternetConnection
    {
    public GeneralUtilsModuleNoInternetConnection() {
    }
    
    @Provides
    @Singleton
    GeneralUtils provideGeneralUtils() {
    
        GeneralUtils mockGeneralUtils = Mockito.mock(GeneralUtils.class);
    
        when(mockGeneralUtils.isInternetConnection()).thenReturn(true);
    
        return mockGeneralUtils;
    }
    }
    

    And in you test class:

        @Test
        public void testOnCreate_whenNoInternetConnection()
        {
           
        }
        @Test
        public void testOnCreate_whenThereIsInternetConnection()
        {
           
        }
    

    Since you are injecting the modules in the test class itself, their scope is just local and you should be just fine.

    Another way is you might just inject one of the modules in setUp. Use it across all the test cases. And just for the test that you need internet connection, inject the GeneralUtilsModuleWithInternetConnection in the test itself.

    Hope this helps.

提交回复
热议问题