0

如何测试依赖于的类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()

4

1 回答 1

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);
于 2016-08-25T05:44:42.780 回答