如何在没有最小起订量的情况下在 C# 中实例化 FormFile 的实例?
How to instantiate an instance of FormFile in C# without Moq?
我想通过集成测试来测试将文件附加到 RavenDB 数据库中的文档的功能。为此,我需要一个 IFormFile
.
的实例
显然,我无法从接口实例化,所以我尝试实例化从 IFormFile
接口继承的 FormFile
的实例。
using (var stream = File.OpenRead("placeholder.pdf"))
{
var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
{
ContentType = "application.pdf"
};
}
但这会引发以下错误:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.AspNetCore.Http.Internal.FormFile.set_ContentType(String value)
当我从代码中删除 ContentType = "application.pdf"
时,它允许我实例化一个新实例但没有 ContentType
。
如何使用 ContentType
而没有 Moq
框架实例化 FormFile
的实例?
感谢汉斯的评论,实际答案是:
using (var stream = File.OpenRead("placeholder.pdf"))
{
var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
{
Headers = new HeaderDictionary(),
ContentType = "application/pdf"
};
}
我想通过集成测试来测试将文件附加到 RavenDB 数据库中的文档的功能。为此,我需要一个 IFormFile
.
显然,我无法从接口实例化,所以我尝试实例化从 IFormFile
接口继承的 FormFile
的实例。
using (var stream = File.OpenRead("placeholder.pdf"))
{
var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
{
ContentType = "application.pdf"
};
}
但这会引发以下错误:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.AspNetCore.Http.Internal.FormFile.set_ContentType(String value)
当我从代码中删除 ContentType = "application.pdf"
时,它允许我实例化一个新实例但没有 ContentType
。
如何使用 ContentType
而没有 Moq
框架实例化 FormFile
的实例?
感谢汉斯的评论,实际答案是:
using (var stream = File.OpenRead("placeholder.pdf"))
{
var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
{
Headers = new HeaderDictionary(),
ContentType = "application/pdf"
};
}