30

我想通过集成测试测试一个将文件附加到 RavenDB 数据库中的文档的函数。为此,我需要一个IFormFile.

显然,我不能从接口实例化,所以我尝试实例化一个FormFile从接口继承的实例IFormFile

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.

如何实例化FormFileContentType和没有Moq框架的实例?

4

1 回答 1

61

感谢汉斯的评论,实际答案是:

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"
    };
}
于 2018-10-12T15:34:15.417 回答