Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 397
Tom Aalbers Avatar asked Aug 06 '18 09:08

Tom Aalbers


1 Answers

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"
    };
}
like image 103
Devator Avatar answered Nov 15 '22 01:11

Devator