49

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?

Tom Aalbers
  • 4,574
  • 5
  • 29
  • 51
  • "without the Moq-framework" By using another framework? Honestly: why don´t you want to use moq in your unit-test-environment? It´s designed exactly for this purpose. – MakePeaceGreatAgain Aug 06 '18 at 09:54
  • Ah sorry my bad. Its an integration test. Updated question. – Tom Aalbers Aug 06 '18 at 10:01
  • 12
    It is pretty low-level, it wants you to set the Headers property first. https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.headerdictionary?view=aspnetcore-2.1 – Hans Passant Aug 06 '18 at 10:04

1 Answers1

95

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"
    };
}
Devator
  • 3,686
  • 4
  • 33
  • 52