Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC 4 WebApi - Testing MIME Multipart Content

I have an ASP.net MVC 4 (beta) WebApi that looks something like this:

    public void Post()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        IEnumerable<HttpContent> parts = Request.Content.ReadAsMultipartAsync().Result;

        // Rest of code here.
    }

I am trying to unit test this code, but can't work out how to do it. Am I on the right track here?

    [TestMethod]
    public void Post_Test()
    {
        MultipartFormDataContent content = new MultipartFormDataContent();
        content.Add(new StringContent("bar"), "foo");

        this.controller.Request = new HttpRequestMessage();
        this.controller.Request.Content = content;
        this.controller.Post();
    }

This code is throwing the following exception:

System.AggregateException: One or more errors occurred. ---> System.IO.IOException: Unexpected end of MIME multipart stream. MIME multipart message is not complete. at System.Net.Http.MimeMultipartBodyPartParser.d__0.MoveNext() at System.Net.Http.HttpContentMultipartExtensions.MoveNextPart(MultipartAsyncContext context) at System.Net.Http.HttpContentMultipartExtensions.MultipartReadAsyncComplete(IAsyncResult result) at System.Net.Http.HttpContentMultipartExtensions.OnMultipartReadAsyncComplete(IAsyncResult result)

Any idea what the best way to do this is?

like image 532
Grokys Avatar asked Dec 20 '22 22:12

Grokys


1 Answers

Altough the question was posted a while ago, i just had to deal with te same kind of problem.

This was my solution:

Create a fake implementation of the HttpControllerContext class where you add MultipartFormDataContent to the HttpRequestMessage.

public class FakeControllerContextWithMultiPartContentFactory
{
    public static HttpControllerContext Create()
    {
        var request = new HttpRequestMessage(HttpMethod.Post, "");
        var content = new MultipartFormDataContent();

        var fileContent = new ByteArrayContent(new Byte[100]);
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "Foo.txt"
        };
        content.Add(fileContent);
        request.Content = content;

        return new HttpControllerContext(new HttpConfiguration(), new HttpRouteData(new HttpRoute("")), request);
    }

}

then in your test:

    [TestMethod]
    public void Should_return_OK_when_valid_file_posted()
    {
        //Arrange
        var sut = new yourController();

        sut.ControllerContext = FakeControllerContextWithMultiPartContentFactory.Create();

        //Act
        var result = sut.Post();

        //Arrange
        Assert.IsType<OkResult>(result.Result);
    }
like image 159
Jimmy Hannon Avatar answered Jan 13 '23 05:01

Jimmy Hannon