2017-03-06 66 views
3

我有一個WebAPI使用自定義ExceptionHandler來處理所有異常。我怎麼能單元測試CustomExceptionHandler。任何鉛會有所幫助如何使用MoQ和NUnit在WebAPI 2中爲ExceptionHandler編寫單元測試

public class CustomExceptionHandler : ExceptionHandler 
{ 
    public override void Handle(ExceptionHandlerContext context) 
    { 
     try 
     { 
      context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError, context.Exception)); 
     } 
     catch (Exception) 
     { 
      base.Handle(context); 
     } 
    } 

    public override bool ShouldHandle(ExceptionHandlerContext context) 
    { 
     return true; 
    } 
} 

回答

6

單元測試這個自定義異常處理程序創建由SUT/MUT所需的依賴關係,並行使測試,以驗證預期的行爲。

這是一個簡單的例子,讓你開始。

[TestClass] 
public class CustomExcpetionhandlerUnitTests { 
    [TestMethod] 
    public void ShouldHandleException() { 
     //Arrange 
     var sut = new CustomExceptionHandler(); 
     var exception = new Exception("Hello World"); 
     var catchblock = new ExceptionContextCatchBlock("webpi", true, false); 
     var configuration = new HttpConfiguration(); 
     var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/test"); 
     request.SetConfiguration(configuration); 
     var exceptionContext = new ExceptionContext(exception, catchblock, request); 
     var context = new ExceptionHandlerContext(exceptionContext); 

     Assert.IsNull(context.Result); 

     //Act 
     sut.Handle(context); 

     //Assert 
     Assert.IsNotNull(context.Result); 
    } 
} 

對於上述試驗中,只將必要的依賴關係,以便行使測試中提供。被測方法(mut)對ExceptionHandlerContext有一個依賴。在將該類傳遞給mut之前,爲該測試提供了該類的最小依賴關係。

斷言可以擴展以適應預期的行爲。

由於沒有任何依賴關係是抽象的,Moq將不能包裝它們。然而,這並沒有阻止所需類的手動實例化。