I am working with ASP.NET/.NET 4.8 application.
My action method is as follows:
public class TestController: System.Web.Http.ApiController
{
// pseudo code
public async Task<IHttpActionResult> Upload()
{
var request = HttpContext.Current.Request;
var file = request.Files[0];//I want to mock this
}
}
How to mock a HttpRequest which has a file in it?
var mockedRequest = new Mock<HttpRequest>();//not allowed: Type to mock (HttpRequest) must be an interface, a delegate, or a non-sealed, non-static class.
I wonder if both HttpContext and HttpRequest classes are sealed and does not inherit from anything, then how does .NET itself creates objects of these classes (n00b question).
As a workaround, I am trying to construct HttpRequest object. Unfortunately it has only one constructor and it does not take Files as parameter:
var Request = new HttpRequest("Upload", "https://www.google.com", "Id=1");
HttpContext.Current = new HttpContext(
Request, new HttpResponse(new StringWriter())
);
How do I set this FormData to the HttpRequest object?
string filePath = @"D:\login.txt";
var form = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(fileContent, "file", Path.GetFileName(filePath));
Or is there any other way to mock HttpRequest?
Update
I realize HttpContext and HttpRequest has no base class and isn't virtual, and hence is unusable for testing, cannot mock it.
https://www.splinter.com.au/httpcontext-vs-httpcontextbase-vs-httpcontext/
I wonder how do I test my code