问题
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