2016-12-03 73 views
1

我在ASP.NET核心應用程序創建一個簡單的動作過濾器,這個動作過濾器假設來記錄用戶的活動:如何在ASP.NET Core中測試自定義操作篩選器?

public class AuditAttribute : IResultFilter 
{ 
    private readonly IAuditService _audit; 
    private readonly IUnitOfWork _uow; 
    public AuditAttribute(IAuditService audit, IUnitOfWork uow) 
    { 
     _audit = audit; 
     _uow = uow; 
    } 
    public void OnResultExecuting(ResultExecutingContext context) 
    { 
     ar model = new Audit 
     { 
      UserName = context.HttpContext.User, 
      //... 
     }; 
     _audit.Add(model); 
     _uow.SaveChanges(); 
    } 
    public void OnResultExecuted(ResultExecutedContext context) 
    { 
    } 
} 

現在,我只是想知道我可以爲它編寫單元測試。我正在使用xUnitMock

+0

模擬所有必要的依賴關係,在測試題的方法,然後驗證與實際行爲 – Nkosi

+1

預期的行爲,在同一方向恩科西說,我會按照AAA模式。 Arrange Act Assert 看看這裏如何測試你的控制器 https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/testing – DOMZE

回答

0

根據您的代碼,要做單元測試,您還需要模擬HttpContext。 順便說一句,這一點似乎不對:UserName = context.HttpContext.User我想你的意思是UserName = context.HttpContext.User.Identity.Name。反正你這是怎麼測試方法應該是這樣的:

public void OnResultExecuting_Test() 
{ 
    // Arrange sesction : 
    var httpContextWrapper = new Moq<HttpContextBase>(); 
    var genericIdentity = new GenericIdentity("FakeUser","AuthType"); 
    var genericPrincipal = new GenericPrincipal(genericIdentity , new string[]{"FakeRole"}); 
    httpContextWrapper.Setup(o=> o.User).Return(genericPrincipal); 
    var controller = new FakeController(); // you can define a fake controller class in your test class (should inherit from MVC Controller class) 
    controller.controllerContext = new ControllerContext(httpContextWrapper.Object, new RouteData(), controller); 
    var audit = new Moq<IUnitOfWork>(); 
    var uow = new Moq<IAuditService>(); 
    // more code here to do assertion on audit 
    uow.Setup(o=>o.SaveChanges()).Verifiable(); 
    var attribute= new AuditAttribute(audit.Object,uow.Object); 

    // Act Section: 
    attribute.OnActionExecuting(filterContext); 

    // Assert Section: 
    ... // some assertions 
    uow.Verify(); 

} 
+1

'filterContext'從哪裏來的? – lbrahim

相關問題