How to mock an IFormFile for a unit/integration test in ASP.NET Core?(如何在 ASP.NET Core 中模拟 IFormFile 以进行单元/集成测试?)
问题描述
我想为在 ASP.NET Core 中上传文件编写测试,但似乎找不到模拟/实例化从 IFormFile 派生的对象的好方法.
I want to write tests for uploading of files in ASP.NET Core but can't seem to find a nice way to mock/instantiate 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) {...}
}
...使用被测方法访问 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));
}
}
这篇关于如何在 ASP.NET Core 中模拟 IFormFile 以进行单元/集成测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 ASP.NET Core 中模拟 IFormFile 以进行单元/集成测试?
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 使用 rss + c# 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
