I am new to unit testing/moq and was wondering how this could be done. I have a function that downloads a file from s3 to local. How can I mock this so that it doesn't actually use transferUtility to download anything from s3?
bool downloadFileFromS3(string localPathToSave, string filenameToDownloadAs, string bucketName, string objectKey)
{
try
{
string accessKey = "xxx";
string secretKey = "xxx";
// do stuff before
TransferUtility transferUtility = new TransferUtility(accessKey, secretKey);
transferUtility.Download( Path.Combine(localPathToSave, filenameToDownloadAs), bucketName, objectKey );
// do stuff after
return true;
}
catch (Exception e)
{
// stuff
}
}
I've created the mock but I don't know how to use it for testing the function that I wrote.
[Test]
public void testDownloadFromS3()
{
string filePath = null;
string bucketName = null;
string key = null;
Mock<Amazon.S3.Transfer.TransferUtility> mock = new Mock<Amazon.S3.Transfer.TransferUtility>();
//mock.Setup(x => x.Download(filePath, bucketName, key)).Verifiable();
//Mock.Verify();
}
According to the documentation the
TransferUtilityclass implements theITransferUtilityinterface.If you need to test your
downloadFileFromS3then your code should depend on abstraction, not on concretions as the SOLID's DIP says.Because the
Downloadmethod does not return anything all you need to do is to setup verifyability in case of happy pathObjectproperty to the class which contains thedownloadFileFromS3Downloadmethod has been called in the way we expectTimes.Onceto theVerifyto make sure that theDownloadhas been called exactly once.This is how you can test the unhappy path:
Verifiablecall toThrowsto throw exception whenever it is calledAssert.IsTruetoAssert.IsFalse// stuffreturnsfalse