gpt4 book ai didi

c# - 如何为 ASP.NET Core 中的单元/集成测试模拟 IFormFile?

转载 作者:可可西里 更新时间:2023-11-01 03:04:05 26 4
gpt4 key购买 nike

我想编写用于在 ASP.NET Core 中上传文件的测试,但似乎找不到一种很好的方法来模拟/实例化从 IFormFile 派生的对象。

关于如何做到这一点有什么建议吗?

最佳答案

假设你有一个 Controller ,比如......

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

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

从 ASP.NET Core 3.0 开始,使用 FormFile Class 的实例现在是 IFormFile 的默认实现。

下面是使用 FormFile 类进行相同测试的示例

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

在引入之前FormFile Class或者在不需要实例的情况下,您可以使用 Moq 创建测试模拟流数据的模拟框架。

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

关于c# - 如何为 ASP.NET Core 中的单元/集成测试模拟 IFormFile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36858542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com