如何在 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/