Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test custom action filter in ASP.NET Core?

I have created a simple action filter in my ASP.NET Core application, this action filter is suppose to log user's activity:

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)
    {
    }
}

Now I just wanted to know how can I write unit tests for it. I'm using xUnit and Mock

like image 483
newbie Avatar asked Dec 03 '16 16:12

newbie


1 Answers

The only way I was able to do this was by creating bare-boned concrete classes and testing the HTTPContext result for what I wanted to achieve. Since I was using concrete classes there was no need for Mock

The setup:

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

The test:

[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()));
}

And this worked for me.

like image 113
CatNip44 Avatar answered Sep 24 '22 04:09

CatNip44