Gro*_*kys 4 c# asp.net-mvc asp.net-web-api
我有一个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.
}
Run Code Online (Sandbox Code Playgroud)
我试图对这段代码进行单元测试,但无法解决如何做到这一点.我在这里走在正确的轨道上吗?
[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();
}
Run Code Online (Sandbox Code Playgroud)
此代码抛出以下异常:
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结果)
知道最好的方法是什么?
Jim*_*non 10
尽管这个问题已经发布了,但我只需处理同样的问题.
这是我的解决方案:
创建一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的测试中:
[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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3490 次 |
最近记录: |