0

How to test a class which depends on Provider<>? Please see the code below.

class ToTest {

    @Inject
    Provider<Processor> processorProvider;

    public buildData() {
        processorProvider.get().process();
    }

    class ProcessorProviderImpl implements Provider<Processor> {
        @Inject
        private Handler someHandler;

        public Processor get() {
            return new MyProcessor(somehandler)
        }
    }

    public static class TestModule extends JukitoModule {
        @Override
        protected void configureTest() {
            bind(Processor.class).toProvider(
                    ProcessorInstanceProviderImpl.class);
            bindMock(SubHandler.class).in(TestSingleton.class);
        }
    }

    class Handler {
        @Inject
        private SubHandler subHandler; // this is singleton instance
    }
}

So when I mock subHandler it doesn't work and when I run unit test I am getting a NullPointerException where subHandler.handle() is getting called.

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
sidss
  • 923
  • 1
  • 12
  • 20
  • Possible duplicate of [What is the best way to use Guice and JMock together?](http://stackoverflow.com/questions/2044991/what-is-the-best-way-to-use-guice-and-jmock-together) –  Aug 25 '16 at 05:41

1 Answers1

2

You can use Providers.of() to initialize processorProvider with a provider of your collaborator instance.

https://google.github.io/guice/api-docs/latest/javadoc/index.html?com/google/inject/util/Providers.html

test = new ToTest();
test.processorProvider = Providers.of(processorMock);
frhack
  • 4,862
  • 2
  • 28
  • 25
  • Sorry i have rephrased my question. What if i dont want to mock instance provider, but a dependency of its dependency. – sidss Aug 25 '16 at 05:57
  • 1
    And why you don't want to mock a collaborator !? You have to mock it, it's not a good idea to use the real object. And if you want to mock a " a dependency of its dependency" maybe there is a bad design: you are violating the Law of Demeter https://en.wikipedia.org/wiki/Law_of_Demeter – frhack Aug 25 '16 at 06:07