3

In my application I am using a FactoryModuleBuilder to automatically create instances of some class:

new AbstractModule() {
  @Override
  protected void configure() {
    install(new FactoryModuleBuilder().implement(A.class,B.class).build(A.AFactory.class));
  }
});

In my test I don't really want to use the implementation (class B) so I would like to configure a module so the factory would return a Mockito mock like this:

new AbstractModule() {
  @Override
  protected void configure() {
    install(new FactoryModuleBuilder().implement(A.class,myMockInstance).build(A.AFactory.class));
  }
});

Obviously the above doesn't make sense because implement() tells which implementation is supposed to be used for interface A but I hope it gets my point across that I want the created factory to use my mock object. Then I could use my mock as usual:

Mockito.when(myMockInstance.doStuff()).thenReturn(result);

Is this possible or do I have to create manually a class C implementing A which will act as a mock?

4

1 回答 1

6

为什么要使用 FactoryModuleBuilder?它的存在是为了自动处理@Assisted来自A.AFactorytoB的构造函数的参数,但在测试中你不需要它——特别是如果工厂返回一个模拟。相反,模拟你自己的A.AFactory,并通过 Guice 访问它。

final A myMockInstance = createAMock();
new AbstractModule() {
  @Override protected void configure() {}

  @Provides
  A.AFactory createAFactory() {
    A.AFactory factory = mock(A.AFactory.class);
    when(factory.createA(anyString(), anyInt(), any(Dependency.class)))
        .thenReturn(myMockInstance);
    return factory;
  }
});

@Provides在这里使用了一种方法,但是您可以轻松地编写自己的五行命名A.AFactory并使用 绑定bind(A.AFactory.class).to(AFactoryForTest.class),或者在其他地方设置您的模拟工厂和bind(A.AFactory.class).toInstance(myMockInstance);.

于 2013-10-21T18:23:00.233 回答