2017-05-10 104 views
1

我有一個專用模塊,其配置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); 
    } 
}); 

和我的錯誤,我不能用空的對象實例化。解決這個問題有什麼更好的方法?我想要以錯誤的方式接近它。

回答

0

您需要確保注入器是在模擬之後創建的。代替使用@Mock註釋,我會創建一個方法,如:

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

    Injector injector = // ... 
}