我有支持上传文件的 Controller 。它里面是一个验证文件中数据的方法。
IEnumerable<ValidationResult> Validate(ICollection<IFormFile> files)
它工作得很好。现在我需要为这个 Controller 编写测试。我的问题是:如何以 FormFile 格式将文件形式的光盘传送到我的函数中?
请您参考如下方法:
通常,将这样的东西实现为接口(interface)的原因是帮助您能够对其进行测试。
您可以轻松编写一个实现 IFormFile 的测试类,以从测试传递给您的 Controller 方法
public class TestFormFile : IFormFile
{
// Implementation here
}
参见 documentation对于您必须实现的所有属性和方法。
你的实现可能应该在构造函数中获取你的字符串内容,并在 IFormFile 上实现 3 种方法时使用它 - 例如 OpenReadStream 的方法可以用使用 MemoryStream(注意,您需要知道测试字符串的编码!):
public class TestFormFile : IFormFile
{
private string testFileContents;
public TestFormFile(string testFileContent)
{
this.testFileContents = testFileContents;
}
public Stream OpenReadStream()
{
return new MemoryStream(Encoding.UTF8.GetBytes(testFileContents));
}
// Implement Other methods and properties.
}
