Mocking Guice提供了对象

时间:2017-05-10 15:33:51

标签: java unit-testing mockito amazon-dynamodb

我有一个特定于应用程序的模块,它是configure DynamoDBMapper,另一类是依赖于该映射器的应用程序

public class ProjectAppServiceModule extends AbstractModule {

  @Override protected void configure() {
  }

  @Provides
  @Singleton
  public AmazonDynamoDB getAmazonDynamoDBClient() {
    return AmazonDynamoDBClientBuilder
            .standard()
            .withCredentials(new EnvironmentVariableCredentialsProvider())
            .build();
  }

  @Provides
  @Singleton
  public DynamoDBMapper getDynamoDBMapper() {
    return new DynamoDBMapper(getAmazonDynamoDBClient());
  }

  @Provides
  @Singleton
  public OrdersManager getOrdersManager() {
    return new OrdersManager(getDynamoDBMapper());
  }

}

现在,我想进行单元测试,在单元测试中,我希望得到一个模拟对象OrderManager

我试过

@Mock
private DynamoDBMapper mockDynamoDBMapper;

Injector injector = createInjector(new AbstractModule() {
    @Override
    protected void configure() {
        bind(DynamoDBMapper.class).toInstance(mockDynamoDBMapper)
       bind(OrdersManager.class).toInstance(mockOrdersManager);
    }
});

我得到了错误,我无法使用null对象进行实例化。什么是解决这个问题的更好方法?我想是以错误的方式接近它。

1 个答案:

答案 0 :(得分:0)

您需要确保在模拟后创建注入器。我将创建一个方法,而不是使用@Mock注释:

@Before
public void before() {
    DynamoDBMapper mockDynamoDBMapper = mock(DynamoDBMapper.class);

    Injector injector = // ...
}