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?
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);
    }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With