依赖于Guice Provider <t>的测试类

时间:2016-08-25 05:34:49

标签: java mockito guice jukito

如何测试依赖Provider<>的课程? 请参阅下面的代码。

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
    }
}

因此,当我模拟subHandler它不起作用时,当我运行单元测试时,我得到一个NullPointerException,其中subHandler.handle()被调用。

1 个答案:

答案 0 :(得分:2)

您可以使用Providers.of()与协作者实例的提供程序初始化processorProvider。

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);