2014-12-28 2 views
2

Как я могу проверить возвращаемое значение метода «ProcessRequest» в общем обработчике с модулем Test?Единичное тестирование общих обработчиков

public class Handler1 : IHttpHandler 
{ 

    public void ProcessRequest(HttpContext context) 
    { 
     context.Response.ContentType = "text/plain"; 
     context.Response.Write("Hello World"); 
    } 

    public bool IsReusable 
    { 
     get 
     { 
      return false; 
     } 
    } 
} 
+0

Что такое ваше утверждение? – haim770

+0

Assert.AreEqual («Hello World», результат); утверждение в ответ – sadeghhp

+0

Покажите текущий код модуляции. Как создается «HttpContext»? – haim770

ответ

2

Вместо того, чтобы использовать макет, попробуйте создать тест HttpContext с SimpleWorkerRequest так:

SimpleWorkerRequest testRequest = new SimpleWorkerRequest("","","", null, new StringWriter()); 
HttpContext testContext = new HttpContext(testRequest); 
HttpContext.Current = testContext; 

Затем вы можете создать свой обработчик и предоставить TestContext методу ProcessRequest:

var handler = new Handler1(); 
handler.ProcessRequest(testContext); 

Затем вы можете проверить HttpContext.Current.Response, чтобы сделать утверждение о своем тесте.

UPDATE:

Я прилагаю полный пример работы модульного тестирования (реализация OutputFilterStream был взят из here):

[TestFixture] 
    [Category("Unit")] 
    public class WhenProcessingRequest 
    { 
     public class Handler1 : IHttpHandler 
     { 

      public void ProcessRequest(HttpContext context) 
      { 
       context.Response.ContentType = "text/plain"; 
       context.Response.Write("Hello World"); 
      } 

      public bool IsReusable 
      { 
       get 
       { 
        return false; 
       } 
      } 
     } 

     public class OutputFilterStream : Stream 
     { 
      private readonly Stream InnerStream; 
      private readonly MemoryStream CopyStream; 

      public OutputFilterStream(Stream inner) 
      { 
       this.InnerStream = inner; 
       this.CopyStream = new MemoryStream(); 
      } 

      public string ReadStream() 
      { 
       lock (this.InnerStream) 
       { 
        if (this.CopyStream.Length <= 0L || 
         !this.CopyStream.CanRead || 
         !this.CopyStream.CanSeek) 
        { 
         return String.Empty; 
        } 

        long pos = this.CopyStream.Position; 
        this.CopyStream.Position = 0L; 
        try 
        { 
         return new StreamReader(this.CopyStream).ReadToEnd(); 
        } 
        finally 
        { 
         try 
         { 
          this.CopyStream.Position = pos; 
         } 
         catch { } 
        } 
       } 
      } 


      public override bool CanRead 
      { 
       get { return this.InnerStream.CanRead; } 
      } 

      public override bool CanSeek 
      { 
       get { return this.InnerStream.CanSeek; } 
      } 

      public override bool CanWrite 
      { 
       get { return this.InnerStream.CanWrite; } 
      } 

      public override void Flush() 
      { 
       this.InnerStream.Flush(); 
      } 

      public override long Length 
      { 
       get { return this.InnerStream.Length; } 
      } 

      public override long Position 
      { 
       get { return this.InnerStream.Position; } 
       set { this.CopyStream.Position = this.InnerStream.Position = value; } 
      } 

      public override int Read(byte[] buffer, int offset, int count) 
      { 
       return this.InnerStream.Read(buffer, offset, count); 
      } 

      public override long Seek(long offset, SeekOrigin origin) 
      { 
       this.CopyStream.Seek(offset, origin); 
       return this.InnerStream.Seek(offset, origin); 
      } 

      public override void SetLength(long value) 
      { 
       this.CopyStream.SetLength(value); 
       this.InnerStream.SetLength(value); 
      } 

      public override void Write(byte[] buffer, int offset, int count) 
      { 
       this.CopyStream.Write(buffer, offset, count); 
       this.InnerStream.Write(buffer, offset, count); 
      } 
     } 


     [Test] 
     public void should_write_response() 
     { 
      //arrange 
      SimpleWorkerRequest testRequest = new SimpleWorkerRequest("", "", "", null, new StringWriter());     
      HttpContext testContext = new HttpContext(testRequest);     
      testContext.Response.Filter = new OutputFilterStream(testContext.Response.Filter);     

      //act 
      var handler = new Handler1(); 
      handler.ProcessRequest(testContext);     
      testContext.Response.End();//end request here(if it is not done in your Handler1) 

      //assert 
      var result = ((OutputFilterStream)testContext.Response.Filter).ReadStream(); 
      Assert.AreEqual("Hello World", result); 
     } 
    } 
+0

безупречный! но как получить «Hello World!» строка? – sadeghhp

+0

Как оказалось, нет «простого» способа извлечения ответа из HttpContext.Current.Response. Но это [выполнимо] (http://stackoverflow.com/questions/16189834/read-httpcontext-current-response-outputstream-in-global-asax?lq=1). Вам нужно создать фильтр для отклика. К сожалению, сегодня у меня нет VS под рукой, чтобы попробовать. – ialekseev

+1

@sadeghhp, я только что обновил ответ, чтобы включить полностью рабочий блок-тест. – ialekseev

Смежные вопросы