Unit testing for uploading to S3

Viewed 23774

I'm having trouble writing unit tests for a method that overwrites a file to a S3 bucket. The method grabs the original metadata of the file, and then overwrites the file with a new modified version and the same original metadata.

What I want the test to do is verify the inner methods like getObjectMetadata and putObject are called correctly with the right parameters

Here is the method:

 public void upload(File file, String account, String bucketName) {
        String key = "fakekey";
        ObjectMetadata objMData = client.getObjectMetadata(bucketName, key).clone();
        try {
            // cloning metadata so that overwritten file has same metadata as original file
            client.putObject(new PutObjectRequest(bucketName, key, file).withMetadata(objMData));
        } catch(AmazonClientException e) {
            e.printStackTrace();
        } 

Here is my test method:

@Mock
private AmazonS3 client = new AmazonS3Client();

public void testUpload() {

    S3Uploader uploader = new S3Uploader(client);

    File testFile = new File("file.txt");
    String filename = "file.txt";
    String bucketname = "buckettest";
    String account = "account";

    String key = account+filename;
    ObjectMetadata objMetadata = Mockito.mock(ObjectMetadata.class);
    when(client.getObjectMetadata(bucketname, key).clone()).thenReturn(objectMetadata);

    // can I make this line do nothing? doNothing()??
    doNothing.when(client.putObject(Matchers.eq(new PutObjectRequest(bucketName, key, file).withMetadata(objMData))));

    uploader.upload(aFile, anAccount, bucketName);

    // how do I verify that methods were called correctly??
    // what can I assert here?

}

I'm getting a NullPointerException at the line in my test

when(client.getObjectMetadata(bucketname, key).clone()).thenReturn(objectMetadata);

I'm not even able to reach the method call. Honestly, what I'm pretty much asking is, how do I verify that this upload() method is correct?

2 Answers
Related