How to mock ActionExecutingContext with Moq?

后端 未结 2 1152
长情又很酷
长情又很酷 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 {}); // if you are reading any properties from the query parameters
    
        var actionContext = new ActionContext(
            httpContextMock,
            Mock.Of(),
            Mock.Of(),
            modelState
        );
    
        var actionExecutingContext = new ActionExecutingContext(
            actionContext,
            new List(),
            new Dictionary(),
            Mock.Of()
        )
        {
            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(), It.IsAny())).ReturnsAsync(true);
    
        var context = new ActionExecutedContext(actionContext, new List(), Mock.Of());
    
        await _classUnderTest.OnActionExecutionAsync(actionExecutingContext, async () => { return context; });
    
        actionExecutingContext.Result.Should().BeOfType();
    }
    

提交回复
热议问题