且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 ASP.NET Core 中为单元/集成测试模拟 IFormFile?

更新时间:2022-03-17 23:14:30

假设你有一个像..

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

...其中 IFormFile.OpenReadStream() 使用被测方法访问.

...where the IFormFile.OpenReadStream() is accessed with the method under test.

您可以使用 Moq 模拟框架创建测试来模拟流数据.

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));
    }
}

或者,从 ASP.NET Core 3.0 开始,使用 FormFile 类,它现在是 IFormFile 的默认实现.

Or, as of ASP.NET Core 3.0, use an instance of the FormFile Class which is now the default implementation of IFormFile.

以下是使用 FormFile 类进行上述相同测试的示例

Here is an example of the same test above using FormFile class

[TestClass]
public class IFormFileUnitTests {
    [TestMethod]
    public async Task Should_Upload_Single_File() {
        //Arrange
       
        //Setup mock file using a memory stream
        var content = "Hello World from a Fake File";
        var fileName = "test.pdf";
        var stream = new MemoryStream();
        var writer = new StreamWriter(stream);
        writer.Write(content);
        writer.Flush();
        stream.Position = 0;

        //create FormFile with desired data
        IFormFile file = new FormFile(stream, 0, stream.Length, "id_from_form", fileName);
        
        MyController sut = new MyController();
        
        //Act
        var result = await sut.UploadSingle(file);

        //Assert
        Assert.IsInstanceOfType(result, typeof(IActionResult));
    }
}