How to instantiate an instance of FormFile in C# without Moq?

♀尐吖头ヾ 提交于 2019-11-29 19:06:23

问题


I want to test a function that attaches files to documents in a RavenDB database with an integration test. For this, I need an instance of IFormFile.

Obviously, I can't instantiate from an interface so I tried to instantiate an instance of FormFile which inherits from the IFormFile interface.

using (var stream = File.OpenRead("placeholder.pdf"))
{
    var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
    {
        ContentType = "application.pdf"
    };
}

But this throws the following error:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.AspNetCore.Http.Internal.FormFile.set_ContentType(String value)

When I remove the ContentType = "application.pdf" from the code it allows me to instantiate a new instance but without a ContentType.

How do I instantiate an instance of FormFile with the ContentType and without the Moq framework?


回答1:


Thanks to Hans his comment, the actual answer is:

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"
    };
}


来源:https://stackoverflow.com/questions/51704805/how-to-instantiate-an-instance-of-formfile-in-c-sharp-without-moq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!