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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With