fabioCollini / DaggerMock

A JUnit rule to easily override Dagger 2 objects
Apache License 2.0
1.16k stars 91 forks source link

Mocking Dagger subcomponents #6

Closed sergiomarqmoura closed 8 years ago

sergiomarqmoura commented 8 years ago

Hi,

I am trying to setup a DaggerMockRule where UserComponent is a @Subcomponent. Due to that, there isn't a DaggerUserComponent being generated, and my test fails because it cannot find DaggerUserComponent.

Is it possible to apply rules to Subcomponents ?

fabioCollini commented 8 years ago

Hi, looking at the generated code it seems that subcomponents are not flexible as normal components. They are created in generated class:

@Override
public MySubComponent mySubComponent() {  
  return new MySubComponentImpl();
}

MySubComponentImpl is generated, it creates the module in the constructor:

private final class MySubComponentImpl implements MySubComponent {
  private final MyModule2 myModule2;

  private MySubComponentImpl() {  
    this.myModule2 = new MyModule2();
    initialize();
  }

  private void initialize() {  
  }

  @Override
  public MainService mainService() {  
    return DaggerMyComponent.this.mainServiceProvider.get();
  }
}

And the module must contain a constructor with no parameters.

So I think that unfortunately DaggerMock cannot be used to override objects in subcomponents. :( But I have never used subcomponents in real projects, any ideas how to implement it are welcome.

sergiomarqmoura commented 8 years ago

Yeah, I understood that in order to use DaggerMock we can't count on subcomponents. Or at least mock them. Thank you!

fabioCollini commented 8 years ago

Hi, I have found a way to support Subcomponents! You can find more info in the README and a new demo project that uses subcomponents.