如何根据服务调用模拟私有成员变量

时间:2016-05-26 15:51:47

标签: java unit-testing junit mockito

我想在Java中模拟DataClient类的对象。我不知道如何在这里模拟s3成员变量。我来自红宝石背景,我们有一些名为rspec-mock的东西,我们不需要模拟实例变量。

public class DataClient {

  private String userName, bucket, region, accessKey, secretKey;
  private AmazonS3Client s3;

  public OdwClient(String accessKey, String secretKey, String userName, String bucket, String region){
    this.accessKey = accessKey;
    this.accessKey = secretKey;
    this.userName = userName;
    this.bucket = bucket;
    this.region = region;
    this.s3 = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));
  }

  public boolean pushData(String fileName) {
    s3.putObject(new PutObjectRequest("bucketName", fileName, new File("filePath")).
    return true;
  }
}

我现在尝试的只是在测试中:

    @Before
    public void setUp() throws Exception{
      DataClient client = Mockito.mock(DataClient.class);
    }

    @Test
    public void testPushData() {
      // I don't know how to mock s3.putObject() method here
    }

我的测试一直都失败了。

2 个答案:

答案 0 :(得分:2)

您遇到的问题是因为您没有使用依赖注入。模拟背后的整个想法是为外部依赖创建模拟对象。为此,您需要为对象提供这些外部依赖项。这可以作为构造函数参数或参数,或通过依赖注入框架来完成。

以下是如何重写课程以使其更具可测试性:

public class DataClient {

  private String userName, bucket, region, accessKey, secretKey;
  private AmazonS3Client s3;

  public OdwClient(String accessKey, String secretKey, String userName, String bucket, String region){
    this(accessKey, secretKey, userName, bucket, region, new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));
  }

  public OdwClient(String accessKey, String secretKey, String userName, String bucket, String region, AmazonS3Client s3){
    this.accessKey = accessKey;
    this.accessKey = secretKey;
    this.userName = userName;
    this.bucket = bucket;
    this.region = region;
    this.s3 = s3;
  }

  public boolean pushData(String fileName) {
    s3.putObject(new PutObjectRequest("bucketName", fileName, new File("filePath")).
    return true;
  }
}

然后,您可以使用真实的DataClient实例而不是模拟,并模拟新DataClient构造函数的s3实例。模拟AmazonS3Client实例后,您可以使用典型的模拟工具从其方法中提供预期的响应。

答案 1 :(得分:1)

您可以使用PowerMock扩展模拟AmazonS3Client类的实例化。

的一些方面
myMockedS3Client = Mockito.mock(AmazonS3Client.class)
PowerMockito.whenNew(AmazonS3Client.class).thenReturn(myMockedS3Client)