2016-12-03 115 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

相关问题