c# mocking IFormFile CopyToAsync() method

徘徊边缘 提交于 2019-12-05 10:11:58
nvoigt

I know this might be unpopular because using a mock framework is totally "in" these days, but why not simply leave the framework be framework and go the simple, easy way? You can create a FormFile without any mocking. Just the real deal:

var fileConverter = new FilesConverter(FilesConverterLoggerMock.Object, FileDataMock.Object);

// access to a real file should really not be in a "unit" test, but anyway: 
using (var stream = new MemoryStream(File.ReadAllBytes("Files/uploadme.txt"))
{
  // create a REAL form file
  var formFile = new FormFile(stream , 0, stream.Length, "name", "filename");

  //Act
  var result = await fileConverter.ConvertFormFilesToFiles(new List<IFormFile> { formFile });

  //Assert
  Assert.IsTrue(result.Any());
}

The problem is that the await formFile.CopyToAsync(memoryStream, CancellationToken.None) doesn't copy any data to the memoryStream.

According to your setup. Nothing will actually be copied.

You just setup the call to return as completed. No actual functionality was implemented.

You'll need to add a Callback to perform some desired functionality before returning the task.

FormFileMock
    .Setup(_ => _.CopyToAsync(It.IsAny<Stream>(), CancellationToken.None))
    .Callback<Stream, CancellationToken>((stream, token) => {
        //memory stream in this scope is the one that was populated
        //when you called **fileStream.CopyTo(memoryStream);** in the test
        memoryStream.CopyTo(stream);
    }) 
    .Returns(Task.CompletedTask);

I combined the answers of @Nkosi and @nvoigt. As @nvoigt pointed out: access to a real file should really not be in a "unit" test. So I replaced the file with a byte array like so:

using (var memoryStream = new MemoryStream(new byte[]{1,2,3,4}))

Instead of a complete file.

And I implemented the .callback on the mocked object as suggested by @Nkosi

FormFileMock.Setup(f => f.CopyToAsync(It.IsAny<Stream>(), CancellationToken.None))
    .Callback<Stream, CancellationToken>((stream, token) =>
    {
        // with memoryStream being the stream from inside the using statement
        memoryStream.CopyTo(stream);
    }).Returns(Task.CompletedTask);

And now it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!