Mockito在使用when时抛出NotAMockException

时间:2017-10-23 21:41:16

标签: java unit-testing amazon-web-services mockito

这是我第一次使用Mockito,请参阅下面的代码。我的目标是确保代码抛出SecureStorageException

我正在努力与来自以下一行的NotAMockException

Mockito.doThrow(AmazonS3Exception.class).when(client).
getObject(Mockito.any(GetObjectRequest.class));

我试过Mockito.spy,但可能我没有正确使用此选项。因此,下面的代码不包括此间谍选项。

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
...
public class S3Test {
private static final String DEFAULT_S3_ENDPOINT = "s3-external-1.amazonaws.com";
private static final String S3_FILE_NOT_FOUND_ERROR_CODE = "NoSuchKey";
public static String S3_BUCKET_NAME = "aaa-test-" + Id.id();

@Mock
private AmazonS3 client;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    client = AmazonS3ClientBuilder.standard()
            .withEndpointConfiguration(new EndpointConfiguration(DEFAULT_S3_ENDPOINT, Regions.US_EAST_1.getName()))
            .build();
}

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void testGetObjectWithAmazonS3Exception() {
    Mockito.doThrow(AmazonS3Exception.class).when(client).getObject(Mockito.any(GetObjectRequest.class));
    thrown.expect(SecureStorageException.class);
    String fileName = Id.id();
    Object obj = (S3Object) call(() -> client.getObject(new GetObjectRequest(S3_BUCKET_NAME, fileName)));
    System.out.println("Obj=" + obj);
}

private Object call(Callable code) {
    try {
        return code.call();
    } catch (AmazonServiceException ase) {
...

0 个答案:

没有答案