ASP.net MVC 4的WebAPI - 测试MIME多内容(ASP.net MVC 4 We

2019-09-16 23:02发布

我有一个ASP.net MVC 4(测试版)的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的结果)

任何想法如何做到这一点的最好办法是什么?

Answer 1:

Altough的问题是前一段时间发布的,我不得不应付TE同样的问题。

这是我的解决方案:

创建一个假的实现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);
    }


文章来源: ASP.net MVC 4 WebApi - Testing MIME Multipart Content