fabioCollini / DaggerMock

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

Mini hack for component builder support #48

Open ohadnav opened 7 years ago

ohadnav commented 7 years ago

Since you can't mock dagger components (they are final), here is a little hack:

               if (moduleName.startsWith("Dagger")) {
                    moduleName = moduleName.substring(6);
                    for (Class<?> interfaceClass : moduleClass.getInterfaces()) {
                        if (Objects.equals(interfaceClass.getSimpleName(), moduleName)) {
                            moduleClass = interfaceClass;
                        }
                    }
                }

Within getSetterMethod under ObjectWrapper

And final tweak to DaggerMockRule in initComponent

private ObjectWrapper<Object> initComponent(ComponentClassWrapper<?> componentClass,
      List<Object> modules, ModuleOverrider moduleOverrider) {
    Class<Object> daggerComponent = componentClass.getDaggerComponentClass();
    ObjectWrapper<Object> builderWrapper =
        ObjectWrapper.invokeStaticMethod(daggerComponent, "builder");
    for (Object module : modules) {
      builderWrapper = builderWrapper.invokeBuilderSetter(module.getClass(),
          (module.getClass().getModifiers() & FINAL) == FINAL ? module
              : moduleOverrider.override(module));
    }
    return builderWrapper;
  }

Happy testing :-)

fabioCollini commented 7 years ago

Could you please provide an example of a test that fails without this modification? Thanks for your suggestion, I'll try to integrate it soon!

ohadnav commented 7 years ago

Whenever a module is dependent on a non-mockable class (i.e. another component).

On Thu, Jul 20, 2017 at 11:46 PM Fabio Collini notifications@github.com wrote:

Could you please provide an example of a test that fails without this modification? Thanks for your suggestion, I'll try to integrate it soon!

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/fabioCollini/DaggerMock/issues/48#issuecomment-316824846, or mute the thread https://github.com/notifications/unsubscribe-auth/AK-E01j3Y-9FZ9a35jKgLOd8G2JiHS-rks5sP7ydgaJpZM4OZZ_k .