How to mock ActionExecutingContext with Moq?
I just stumbled on the same problem and solved it in this way.
[Fact]
public void ValidateModelAttributes_SetsResultToBadRequest_IfModelIsInvalid()
{
var validationFilter = new ValidationFilter();
var modelState = new ModelStateDictionary();
modelState.AddModelError("name", "invalid");
var actionContext = new ActionContext(
Mock.Of<HttpContext>(),
Mock.Of<RouteData>(),
Mock.Of<ActionDescriptor>(),
modelState
);
var actionExecutingContext = new ActionExecutingContext(
actionContext,
new List<IFilterMetadata>(),
new Dictionary<string, object>(),
Mock.Of<Controller>()
);
validationFilter.OnActionExecuting(actionExecutingContext);
Assert.IsType<BadRequestObjectResult>(actionExecutingContext.Result);
}
If someone was wondering how to do this when you inherit from IAsyncActionFilter
[Fact]
public async Task MyTest()
{
var modelState = new ModelStateDictionary();
var httpContextMock = new DefaultHttpContext();
httpContextMock.Request.Query = new QueryCollection(new Dictionary<string, StringValues> {}); // if you are reading any properties from the query parameters
var actionContext = new ActionContext(
httpContextMock,
Mock.Of<RouteData>(),
Mock.Of<ActionDescriptor>(),
modelState
);
var actionExecutingContext = new ActionExecutingContext(
actionContext,
new List<IFilterMetadata>(),
new Dictionary<string, object>(),
Mock.Of<Controller>()
)
{
Result = new OkResult() // It will return ok unless during code execution you change this when by condition
};
Mymock1.SetupGet(x => x.SomeProperty).Returns("MySomething");
Mymock2.Setup(x => x.GetSomething(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(true);
var context = new ActionExecutedContext(actionContext, new List<IFilterMetadata>(), Mock.Of<Controller>());
await _classUnderTest.OnActionExecutionAsync(actionExecutingContext, async () => { return context; });
actionExecutingContext.Result.Should().BeOfType<OkResult>();
}