How to mock ActionExecutingContext with Moq?

后端 未结 2 1153
长情又很酷
长情又很酷 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 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(),
            Mock.Of(),
            Mock.Of(),
            modelState
        );
    
        var actionExecutingContext = new ActionExecutingContext(
            actionContext,
            new List(),
            new Dictionary(),
            Mock.Of()
        );
    
        validationFilter.OnActionExecuting(actionExecutingContext);
    
        Assert.IsType(actionExecutingContext.Result);
    }
    

提交回复
热议问题