[英]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? 如果文件成功上传到AWS S3存储桶,则最佳的单元测试方法是什么?
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. 方法UploadFile()使用文件流从AWS文档中提取并上传到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. 我不喜欢这种方法,因为它需要一个本地文件(C:\\ test.txt)-因此,如果通过版本控制进行共享,则此单元测试将无法进行。
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? 使用
System.IO.Path.GetTempPath()
创建一个临时文本文件上传并在单元测试中用作比较是否有意义?
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. 与其从磁盘上的文件创建流,
MemoryStream
使用MemoryStream
。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.