Kasper P Kasper P - 4 months ago 103
ASP.NET (C#) Question

How to mock an IFormFile for a unit/integration test in ASP.NET Core 1 MVC 6?

I want to write tests for uploading of files in ASP.NET Core 1 but can't seem to find a nice way to mock/instanciate an object derived from IFormFile.
Any suggestions on how to do this?



Assuming you have a Controller like..

public class MyController : Controller {
    public Task<IActionResult> UploadSingle(IFormFile file) {...}

...where the IFormFile.OpenReadStream() is accessed with the method under test. You can create a test using Moq mocking framework to simulate the stream data.

public class IFormFileUnitTests {
    public async Task Should_Upload_Single_File() {
        var fileMock = new Mock<IFormFile>();
        //Setup mock file using a memory stream
        var s = "Hello World from a Fake File";
        var ms = new MemoryStream();
        var writer = new StreamWriter(ms);
        ms.Position = 0;
        fileMock.Setup(m => m.OpenReadStream()).Returns(ms);

        var sut = new MyController();
        var file = fileMock.Object;
        var result = await sut.UploadSingle(file);
        Assert.IsInstanceOfType(result, typeof(IActionResult));