4

我有一个看起来像这样的 ASP.net MVC 4 (beta) WebApi:

    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.
    }

我正在尝试对这段代码进行单元测试,但不知道该怎么做。我在正确的轨道上吗?

    [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();
    }

此代码引发以下异常:

System.AggregateException:发生一个或多个错误。---> System.IO.IOException:MIME 多部分流意外结束。MIME 多部分消息不完整。在 System.Net.Http.MimeMultipartBodyPartParser.d__0.MoveNext() 在 System.Net.Http.HttpContentMultipartExtensions.MoveNextPart(MultipartAsyncContext 上下文) 在 System.Net.Http.HttpContentMultipartExtensions.MultipartReadAsyncComplete(IAsyncResult 结果) 在 System.Net.Http.HttpContentMultipartExtensions .OnMultipartReadAsyncComplete(IAsyncResult 结果)

知道最好的方法是什么吗?

4

1 回答 1

11

尽管这个问题是不久前发布的,但我只需要处理同样的问题。

这是我的解决方案:

创建 HttpControllerContext 类的假实现,在其中将 MultipartFormDataContent 添加到 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);
    }

}

然后在你的测试中:

    [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);
    }
于 2015-01-15T10:07:57.567 回答