I am working on a unit test for an async function that converts a list of IFormFile to a list of my own arbitrary database file classes.
The method that converts the file data to a byte array is:
internal async Task<List<File>> ConvertFormFilesToFiles(ICollection<IFormFile> formFiles)
{
var file = new File
{
InsertDateTime = DateTime.Now,
LastChangeDateTime = DateTime.Now
};
if (formFile.Length > 0)
{
using (var memoryStream = new MemoryStream())
{
await formFile.CopyToAsync(memoryStream, CancellationToken.None);
file.FileData = memoryStream.ToArray();
}
}
// ...
}
The function receives an ICollection of IFormFiles so it is mockable.
For now I have test code like this:
//Arrange
var fileConverter = new FilesConverter();
using (var fileStream = new FileStream("Files/uploadme.txt", FileMode.Open, FileAccess.Read))
{
using (var memoryStream = new MemoryStream())
{
var newMemoryStream = new MemoryStream();
fileStream.CopyTo(memoryStream);
FormFileMock.Setup(f => f.CopyToAsync(newMemoryStream, CancellationToken.None)).Returns(Task.CompletedTask);
// some other setups
//Act
var result = await fileConverter.ConvertFormFilesToFiles(new List<IFormFile> { FormFileMock.Object });
//Assert
Assert.IsTrue(result.Any());
}
}
The newMemoryStream variable is created because the function calls the CopyToAsync method with a new and empty memorystream (I'm not sure if this is necessary).
The problem is that the await formFile.CopyToAsync(memoryStream, CancellationToken.None) doesn't copy any data to the memoryStream.