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

后端 未结 3 675
有刺的猬
有刺的猬 2020-12-16 11:05

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 ho

相关标签:
3条回答
  • 2020-12-16 11:24

    Adding on harishr's answer with a set lenght (which was what I needed for my Blob.Upload() to work).

    private IFormFile CreateTestFormFile(string p_Name, string p_Content)
    {
        byte[] s_Bytes = Encoding.UTF8.GetBytes(p_Content);
    
        return new FormFile(
            baseStream: new MemoryStream(s_Bytes),
            baseStreamOffset: 0,
            length: s_Bytes.Length,
            name: "Data",
            fileName: p_Name
        );
    }
    
    0 讨论(0)
  • 2020-12-16 11:27

    Easier would be to create an actual in-memory instance

     IFormFile file = new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("This is a dummy file")), 0, 0, "Data", "dummy.txt");
    
    0 讨论(0)
  • 2020-12-16 11:35

    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.

    [TestClass]
    public class IFormFileUnitTests {
        [TestMethod]
        public async Task Should_Upload_Single_File() {
            //Arrange
            var fileMock = new Mock<IFormFile>();
            //Setup mock file using a memory stream
            var content = "Hello World from a Fake File";
            var fileName = "test.pdf";
            var ms = new MemoryStream();
            var writer = new StreamWriter(ms);
            writer.Write(content);
            writer.Flush();
            ms.Position = 0;
            fileMock.Setup(_ => _.OpenReadStream()).Returns(ms);
            fileMock.Setup(_ => _.FileName).Returns(fileName);
            fileMock.Setup(_ => _.Length).Returns(ms.Length);
    
            var sut = new MyController();
            var file = fileMock.Object;
    
            //Act
            var result = await sut.UploadSingle(file);
    
            //Assert
            Assert.IsInstanceOfType(result, typeof(IActionResult));
        }
    }
    
    0 讨论(0)
提交回复
热议问题