简体   繁体   中英

Unit test file upload to AWS S3

What would be the best way to unit test if a file upload to a AWS S3 bucket succeeded?

Right now I am doing the following:

        [Test]
        public void UploadFileToAWS()
        {
            // Arrange
            var bucket = "bucketName";
            var keyName = "test_upload.txt";
            var originalFile = new FileStream(@"C:\test.txt", FileMode.Open, FileAccess.Read);

            // Act
            var aws = new AmazonWebServicesUtility(bucket);
            var awsUpload = aws.UploadFile(keyName,originalFile);

            // Assert
            Assert.AreEqual(true, awsUpload);
        }

The method UploadFile() is taken from the AWS documentation using a FileStream to upload to AWS.

What I do not like about this approach is, that it needs a local file (C:\\test.txt) - so this unit test won't work if shared through version control.
How could I modify this unit test so it doesn't rely on a local file?

Would it make sense to use System.IO.Path.GetTempPath() to create a temporary text file that I upload and use as a comparison in the unit test?

I am fairly new to unit tests, so I am happy for any direction you can point me in :-)

Thank you very much!

Instead of creating a stream from a file on your disk, use a MemoryStream instead. This way, the text you insert into it is a constant in your code and can also be used for downloading the file and testing the entire round trip process. So taking code from this answer :

private const string StringToTestWith = "some sort of test string goes in here";

[Test]
public void UploadFileToAWS()
{
    // Arrange
    var bucket = "bucketName";
    var keyName = "test_upload.txt";
    var uploadFile = GenerateStreamFromString(StringToTestWith);

    // Act
    var aws = new AmazonWebServicesUtility(bucket);
    var awsUpload = aws.UploadFile(keyName, uploadFile);

    // Assert
    Assert.AreEqual(true, awsUpload);
}

private static Stream GenerateStreamFromString(string s)
{
    var stream = new MemoryStream();
    var writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;
}

And now you can write this test too:

[Test]
public void DoesDownloadGetTheCorrectValue()
{
    //This implementation is up to you
    var downloadedString = GetFileFromAWSSomehow();

    Assert.AreEqual(downloadedString, StringToTestWith);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM