Android Unit Tests with Dagger 2

前端 未结 5 1702
死守一世寂寞
死守一世寂寞 2020-12-13 06:08

I have an Android app that uses Dagger 2 for dependency injection. I am also using the latest gradle build tools that allow a build variant for unit testing and one for inst

5条回答
  •  有刺的猬
    2020-12-13 06:22

    In my opinion you can approach this problem by looking at it from a different angle. You will easily be able to unit test your class by not depending upon Dagger for construction class under test with its mocked dependencies injected into it.

    What I mean to say is that in the test setup you can:

    • Mock the dependencies of the class under test
    • Construct the class under test manually using the mocked dependencies

    We don't need to test whether dependencies are getting injected correctly as Dagger verifies the correctness of the dependency graph during compilation. So any such errors will be reported by failure of compilation. And that is why manual creation of class under test in the setup method should be acceptable.

    Code example where dependency is injected using constructor in the class under test:

    public class BoardModelTest {
    
      private BoardModel boardModel;
      private Random random;
    
      @Before
      public void setUp() {
        random = mock(Random.class);
        boardModel = new BoardModel(random);
      }
    
      @Test
      ...
    }
    
    public class BoardModel {
      private Random random;
    
      @Inject
      public BoardModel(Random random) {
        this.random = random;
      }
    
      ...
    }
    

    Code example where dependency is injected using field in the class under test (in case BoardModel is constructed by a framework):

    public class BoardModelTest {
    
      private BoardModel boardModel;
      private Random random;
    
      @Before
      public void setUp() {
        random = mock(Random.class);
        boardModel = new BoardModel();
        boardModel.random = random;
      }
    
      @Test
      ...
    }
    
    public class BoardModel {
      @Inject
      Random random;
    
      public BoardModel() {}
    
      ...
    }
    

提交回复
热议问题