gpt4 book ai didi

c# - ASP.net MVC 4 WebApi - 测试 MIME 多部分内容

转载 作者:太空狗 更新时间:2023-10-30 00:20:36 26 4
gpt4 key购买 nike

我有一个 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: 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)

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

最佳答案

尽管问题是前一段时间发布的,但我只需要处理同类问题。

这是我的解决方案:

创建 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);
}

关于c# - ASP.net MVC 4 WebApi - 测试 MIME 多部分内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10402568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com