I have a .NET Core class library for blob storage, which I use in ASP.NET Core web applications, and I want to test the controller it exposes. For reasons beyond my control, I need to test the controller without using a HTTP client, testing server, or web application, which is why I am trying to mock a request. I need to mock a multipart/form-data HTTP request for a file upload in order to test the POST method of the controller.
I tried to figure out how to mock the request from this article: How to mock the Request on Controller in ASP.Net MVC? but to no avail.
// Controller action
[HttpPost]
[DisableFormValueModelBinding]
public async Task<AttachedFile> Post()
{
return await Request.WriteToFileStorage(service);
}
// Test with mocking
[Fact]
public async Task Post_New()
{
// ...
var controller = new FileStorageController(service);
var content = Convert.FromBase64String(imageBase64);
var request = new Mock<HttpRequest>();
request.SetupGet(x => x.Headers).Returns(
new HeaderDictionary { { "X-Requested-With", "XMLHttpRequest" } });
request.SetupGet(x => x.ContentLength).Returns(1455);
request.SetupGet(x => x.ContentType).Returns("multipart/form-data");
request.SetupGet(x => x.Body).Returns(new MemoryStream(content));
var httpContext = new Mock<HttpContext>();
httpContext.SetupGet(x => x.Request).Returns(request.Object);
controller.ControllerContext = new ControllerContext {
HttpContext = httpContext.Object
};
var result = await controller.Post();
// ...
}
When I try to mock the Request object in some way, the test fails and I get an exception in the test explorer saying "Message: System.IO.InvalidDataException : Missing content-type boundary". How do I properly form the body of the request?