2016-05-26 73 views
2

我想模擬Java中DataClient類的對象。我不知道如何在這裏模擬s3成員變量。我來自ruby背景,我們有一些名爲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 
    } 

我的測試中不斷失敗。

回答

1

您可以使用PowerMock擴展來模擬AmazonS3Client類的實例化。東西沿線

myMockedS3Client = Mockito.mock(AmazonS3Client.class) 
PowerMockito.whenNew(AmazonS3Client.class).thenReturn(myMockedS3Client) 
+0

難道你不是指** PowerMockito.whenNew **? –

+0

@IgorGanapolsky你是對的。更新了答案。 – ccstep1

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實例,而不是一個模擬,並嘲笑S3實例新DataClient構造。在您嘲笑AmazonS3Client實例之後,您可以使用典型的模擬工具從其方法中提供預期的響應。