单元测试 Guice 模块,其中一个模块安装另一个模块

Unit Testing Guice modules where one module installs another module

仅供参考,我正在使用 Mockito 和 TestNg

我知道如何通过使用 @Bind 模拟我的外部依赖项来测试我在 Guice 模块中的逻辑。

这里我有一个模块(比如 Foo),它在 configure 方法中有 install(new Bar());

我可以在Foo里绑定各种外部依赖,但是我不知道Bar里的东西怎么处理

例如)

public class FooTest {

@Bind
@Mock
SomeExternalDependency1 someExternalDependency1;

@Bind
@Mock
SomeExternalDependency2 someExternalDependency2;

@BeforeClass
public void setup() {
    MockitoAnnotations.initiMocks(this);
    injector = Guice.createInjector(Modules.override(new Foo())with(
        new TestFooModule()), BoundFieldModule.of(this));
    injector.injectMembers(this);
}

@Test
public void testSomething() {
    //asssert something here
}

static class TestFooModule extends AbstractModule {
    @Override
    protected void configure() { }
}

但是当我 运行 这个测试时,它抱怨 Bar 中的外部依赖项。

如何在不实例化 Bar 模块的情况下测试 Foo 模块?

对于不安装 'children' 模块的模块,这种测试工作正常。

我需要 bind 来自 TestFooModule 内的 Bar 的 @provides。那解决了我的问题。