java - 使用 Guice 进行模拟并拥有用于测试目的的真实对象

标签 java unit-testing dependency-injection mockito guice

如何在 Guice Test 模块中创建一个对象,该对象在一个测试中用作模拟,但在另一个测试中需要是真实对象。

例如。 假设我有一个名为 ConfigService 的类。使用构造函数注入(inject)将其注入(inject)到另一个名为 UserService 的类中。在测试过程中,我使用具有各种类及其模拟的 TestModule。

TestModule.java:

public class TestModule extends AbstractModule{
    @Override
    public void configure() {
            ConfigService configService = Mockito.mock(ConfigService.class);
            bind(ConfigService.class).toInstance(configService);

            UserService userService = new UserService(configService);

            bind(UserService.class).toInstance(userService);

    }
}

在 UserServiceTest 中,我创建一个注入(inject)器并使用此 TestModule 中的实例。

Injector injector = Guice.createInjector(new TestModule());
userService = injector.getInstance(UserService.class);
configService = injector.getInstance(ConfigService.class);

这工作正常,我现在遇到问题的地方是当我需要测试 ConfigService.class 时。

如果我想对 ConfigServiceTest 使用相同的 TestModule,现在如何将之前创建的 ConfigService 的模拟对象更改为实际的测试对象。反之亦然也是一个问题->即。如果我有一个真实的 ConfigService 对象,我如何 stub 并模拟 UserService.class 中的响应。

有没有办法实现这一点,或者我应该为模拟和真实对象创建单独的测试模块?或者我是否以错误的方式进行整个过程?

最佳答案

您可以使用spy方法来做到这一点。

ConfigService realConfigService = new ConfigService();
ConfigService configService = Mockito.spy(realConfigService);
bind(ConfigService.class).toInstance(configService);

spy 的作用是,每当您提供 stub 时,它的行为就像对象被模拟一样。否则,它将调用该对象的真实方法。

请检查此答案以了解更多 in-depth theory

关于java - 使用 Guice 进行模拟并拥有用于测试目的的真实对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49251631/

相关文章:

java - 从 Java 连接 PHP 时出现 IllegalStateException

java - 如何在通过 curl 命令发送文件时在 Tomcat 服务器中的过滤器期间获取文件名

c# - 乌鸦.Client.Exceptions.Database.DatabaseDoesNotExistException : 'Database ' *****' does not exist

android - 使用 AndroidAnnotations 进行 Robolectric 单元测试

java - 如何使用 Dagger 2 在运行时注入(inject)字段?

c# - 构造函数注入(inject)过度使用

dependency-injection - 我的工厂对象是否引入了全局状态?

c# - 使用工具还是手动将 Java 转换为 C#?

Java Flight Recorder - 如何提取自定义事件字段的值?

java - 不模拟方法,而是调用原始方法(mockito)