不适用于本地变量的模拟 - 获取指定密钥不存在(服务Amazon S3)

时间:2018-05-30 06:24:49

标签: java junit4 powermockito

这是我想要使用mock

测试的实际方法
   @Override
    public void processTransaction(Exchange exchange) throws Exception {
        AmazonS3 s3Client = null;
        s3Client = new AmazonS3Client(new DefaultAWSCredentialsProviderChain());
        url = String.format("%s%s%s", tenantConfig.getSchemaName(), PATH_LOC_NEW, fileName);
        region = System.getProperty("aws.region.prefix") != null ? System.getProperty("aws.region.prefix") : "";
        bucket = String.format("%s%s-%s", System.getProperty("aws.Environment"), region, "gfcp-tenant");
        S3Object object = s3Client.getObject(new GetObjectRequest(bucket, url));
        InputStream inputStream = new BufferedInputStream(object.getObjectContent());
        ObjectMetadata meta = new ObjectMetadata();
    }

这是我的测试逻辑,但它似乎没有嘲笑AmazonS3Client AmazonS3这就是我得到异常的原因

@RunWith(PowerMockRunner.class)
@PrepareForTest({TransactionProcessingService.class})
@PowerMockIgnore({"javax.net.ssl.*","javax.security.*","javax.management.*","javax.crypto.*"})
public class TransactionProcessingServiceTest {

    @Test
    public void testProcessTransaction() throws Exception {
        DefaultAWSCredentialsProviderChain credentialMock = PowerMockito.mock(DefaultAWSCredentialsProviderChain.class);
        PowerMockito.whenNew(DefaultAWSCredentialsProviderChain.class).withNoArguments().thenReturn(credentialMock);
        AmazonS3Client s3Client = PowerMockito.mock(AmazonS3Client.class);
        HttpRequestBase httprequest = PowerMockito.mock(HttpRequestBase.class);
        S3Object object= PowerMockito.mock(S3Object.class);
        InputStream in = PowerMockito.mock(InputStream.class);
        object.setObjectContent(new S3ObjectInputStream(in, httprequest));
        when(s3Client.getObject(new GetObjectRequest("local_vittal-gfcp-tenant", "cdta/TransactionProcessing/New/junit_test_file.acf")))
                            .thenReturn(object);
        PowerMockito.whenNew(AmazonS3Client.class).withArguments(credentialMock).thenReturn(s3Client);
        transactionProcessingService.processTransaction(exchange);

    }   
}

任何人都可以帮助我。 提前致谢

1 个答案:

答案 0 :(得分:0)

现在正在运作。 我还需要在@PrepareForTest中使用实现类,如 -

@PrepareForTest(TransactionProcessingServiceImpl.class)