如何在ASP.NET Core 1 MVC 6中模拟IFormFile进行单元/集成测试? [英] How to mock an IFormFile for a unit/integration test in ASP.NET Core 1 MVC 6?
本文介绍了如何在ASP.NET Core 1 MVC 6中模拟IFormFile进行单元/集成测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写用于在ASP.NET Core 1中上传文件的测试,但是似乎找不到一种模拟/实例化从IFormFile派生的对象的好方法. 有关如何执行此操作的任何建议?
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?
谢谢.
推荐答案
假设您有一个类似Controller ..
Assuming you have a Controller like..
public class MyController : Controller {
public Task<IActionResult> UploadSingle(IFormFile file) {...}
}
...使用测试中的方法访问IFormFile.OpenReadStream()
的位置.您可以使用 Moq 模拟框架来创建测试,以模拟流数据.
...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));
}
}
这篇关于如何在ASP.NET Core 1 MVC 6中模拟IFormFile进行单元/集成测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文