Mockito 和 Guice:模拟 @Provides 方法

Sas*_*uri 5 dependency-injection guice mockito vert.x

我的班级中有一个名为 MainModule 的模块。它有各种绑定,其中之一是绑定到我的名为 HttpClientPool 的自定义服务接口

public class MainModule extends AbstractVertxModule{
        binder.bind(HttpClientPool.class).to(HttpClientPoolImpl.class).in(Singleton.class);
        // other bindings
} 

@Provides @Singleton
    public TokenClient tokenClient(HttpClientPool clientPool){
        return new TokenClient(clientPool);
}
Run Code Online (Sandbox Code Playgroud)

该模块也是一个名为 tokenClient 的对象的提供者,如上所示。

tokenClient 被注入到另一个类中的其他地方,并且在这个对象上调用了一些方法。

在我的单元测试中,我打算使用 Mockito 来获取模拟的 tokenClient 对象。这意味着,我希望 MainModule 提供一个模拟对象,而不是一个真实的对象。我曾尝试使用如下所示的 testMainModule:

public class testMainModile implements Module{
    private TokenClient tokenClient;

    public TokenModule(TokenClient client) {
        this.tokenClient= client;
    }

    @Override
    public void configure(Binder binder) {
        binder.bind(TokenClient.class).toInstance(tokenClient);
    }
}
Run Code Online (Sandbox Code Playgroud)

摘自我的单元测试:

@Mock
private TokenClient tokenClient;
// Stuff between
Injector messagingInjector = Guice.createInjector(new TestMainModule(tokenClient));
        mainModule = messagingInjector.getInstance(MainModule.class);
Run Code Online (Sandbox Code Playgroud)

不知何故,我得到的只是一个来自 mainModule 对象的真实对象。我错过了什么吗?

Jan*_*ski 5

我假设您有一个提供某些功能的类。这是您想要进行单元测试的类。它需要您注入到类中的 tokenClient 才能正常工作。所以你面临的问题是:当我测试我的被测类时,如何获得一个模拟的tokenClient注入。

有几种可能性......可能最简单的一种是仅严格使用构造函数注入并通过“new”创建正在测试的类的实例,然后将它们单独创建的模拟实例交给它们。

如果您想坚持使用 guice,可以覆盖绑定和提供程序,甚至提供完全隔离的测试模块。

我更喜欢使用needle4j框架(我是一个贡献者,所以我有偏见),这是一个依赖注入模拟器,默认情况下注入模拟,除非配置为其他。如果使用正确(坚持一个类单元,不要尝试设置集成级别测试),这可能是根据注入实例测试类的最快、最简单的方法。