没有Moq的情况下如何在C#中实例化FormFile的实例?

时间:2018-08-06 09:47:27

标签: c# .net-core iformfile

我想通过集成测试来测试将文件附加到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

如何在没有FormFile框架的情况下使用ContentType实例化Moq的实例?

1 个答案:

答案 0 :(得分:14)

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

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"
    };
}
相关问题