Mocking IFormFile objects

So you want to unit test a method that processes an IFormFile instance. You can use the concrete FormFile class for this, but you must instantiate the Headers property otherwise it blows up with a NullReferenceException if the code you are trying to test accesses the ContentType or ContentDisposition properties of the IFormFile, or if you are trying to set these properties:

var fileContent = "This is a dummy file";
var bytes = Encoding.UTF8.GetBytes(fileContent);
var invoice = new FormFile(new MemoryStream(bytes), 0, bytes.Length, "Invoice", "invoice.pdf")
{
    Headers = new HeaderDictionary(), // <-- NOTE THIS IS IMPORTANT!!!
    ContentType = MediaTypeNames.Application.Pdf
};
var model = new Pages.Invoicing.ManageInvoice(){
    Amount = 100, 
    DaysDue = 30, 
    InvoiceDate = DateTime.Now, 
    InvoiceId = 1, Invoice = invoice
};

Here's the offending properties' source code:

/// <summary>
/// Gets the raw <c>Content-Disposition</c> header of the uploaded file.
/// </summary>
public string ContentDisposition
{
    get { return Headers.ContentDisposition.ToString(); }
    set { Headers.ContentDisposition = value; }
}
 
/// <summary>
/// Gets the raw <c>Content-Type</c> header of the uploaded file.
/// </summary>
public string ContentType
{
    get { return Headers.ContentType.ToString(); }
    set { Headers.ContentType = value; }
}
Last updated: 8/21/2024 2:16:47 PM

Latest Updates

© 0 - 2025 - Mike Brind.
All rights reserved.
Contact me at Mike dot Brind at Outlook.com