如何在ASP.NET Core中测试自定义动作过滤器?

时间:2016-12-03 16:29:55

标签: c# unit-testing asp.net-core xunit

我在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

2 个答案:

答案 0 :(得分:0)

我能够做到这一点的唯一方法是创建裸露的具体类,并测试HTTPContext结果是否达到我想要的目的。由于我使用的是具体类,因此不需要Mock

设置:

[SetUp]
public void SetUp()
{
   _actionContext = new ActionContext()
   {
      HttpContext = new DefaultHttpContext(),
      RouteData = new RouteData(),
      ActionDescriptor = new ActionDescriptor()
   };
}

测试:

[Test]
public void Should_deny_request()
{
    // Given
    var resourceExecutingContext = new ResourceExecutingContext(_actionContext, new List<IFilterMetadata>(), new List<IValueProviderFactory>());
    var attribute = new YourAttribute();

    // When
    attribute.OnResourceExecuting(resourceExecutingContext);
    var result = (ContentResult) resourceExecutingContext.Result;

    // Then
    Assert.IsTrue(Equals("403", result.StatusCode.ToString()));
}

这对我有用。

答案 1 :(得分:-1)

根据你的代码,要进行单元测试,你还需要模拟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();

 }