2012-05-01 15 views
5

Ho un 4 WebAPI (beta) ASP.net MVC che sembra qualcosa di simile:ASP.net MVC 4 WebAPI - Test MIME Multipart Content

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

Sto cercando di unit test di questo codice, ma può risolvi il modo di farlo Sono sulla strada giusta qui?

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

Questo codice getta la seguente eccezione:

System.AggregateException: Uno o più errori. ---> System.IO.IOException: fine imprevisto del flusso multipart MIME. Il messaggio multipart MIME non è completo. a System.Net.Http.MimeMultipartBodyPartParser.d__0.MoveNext() a System.Net.Http.HttpContentMultipartExtensions.MoveNextPart (MultipartAsyncContext contesto) a System.Net.Http.HttpContentMultipartExtensions.MultipartReadAsyncComplete (IAsyncResult risultato) a System.Net.Http.HttpContentMultipartExtensions.OnMultipartReadAsyncComplete (IAsyncResult risultato)

Qualsiasi idea di ciò che il modo migliore per farlo è?

risposta

10

Anche se la domanda è stata postata qualche tempo fa, ho dovuto affrontare lo stesso tipo di problema.

Questa era la mia soluzione:

Creare un falso implementazione della classe HttpControllerContext in cui si aggiunge MultipartFormDataContent al 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); 
    } 

} 

poi nel 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); 
    } 
+1

Tale metodo è sorprendentemente semplice e più facile da implementare di un sacco di altri quelli che ho visto. – BrianS

+0

nice nice nice! Grazie fratello –

+0

Molto semplice, pulito e carino, grazie! –

Problemi correlati