How to mock ActionExecutingContext with Moq?

后端 未结 2 1148
长情又很酷
长情又很酷 2020-12-08 16:19

I am trying to test the following filter:

using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;

namespace Hello
{
    public class ValidationFilte         


        
相关标签:
2条回答
  • 2020-12-08 16:42

    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>();
    }
    
    0 讨论(0)
  • 2020-12-08 17:06

    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);
    }
    
    0 讨论(0)
提交回复
热议问题