Asp.net mvc 如何使用Moq模拟ActionExecutingContext?

Asp.net mvc 如何使用Moq模拟ActionExecutingContext?,asp.net-mvc,unit-testing,moq,xunit,Asp.net Mvc,Unit Testing,Moq,Xunit,我正在尝试测试以下筛选器: using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc.Filters; namespace Hello { public class ValidationFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext)

我正在尝试测试以下筛选器:

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

namespace Hello
{
    public class ValidationFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.ModelState.IsValid) {
                filterContext.Result = new BadRequestObjectResult(filterContext.ModelState);
            }
        }
    }
}
我试图用Moq来模拟ActionFilterAttribute

我正在使用MVC6.0.0-rc1

我的第一次尝试:

var context = new ActionExecutingContext(
                    new ActionContext(Mock.Of<HttpContext>(), new RouteData(), new ActionDescriptor()),
                    new IFilterMetadata[] { filter, },
                    new Dictionary<string, object>(),
                    controller: new object());

如何测试使用ModelState的过滤器?

我刚刚偶然发现了同样的问题,并用这种方法解决了它

[事实]
public void ValidateModelAttributes_setResultToBadRequest_IfModelIsInvalid()
{
var validationFilter=新的validationFilter();
var modelState=new ModelStateDictionary();
AddModelError(“名称”、“无效”);
var actionContext=新的actionContext(
Mock.Of(),
Mock.Of(),
Mock.Of(),
模型状态
);
var actionExecutingContext=新的actionExecutingContext(
行动背景,
新列表(),
新字典(),
模仿
);
validationFilter.OnActionExecuting(actionExecutingContext);
IsType(actionExecutingContext.Result);
}

如果当您从
IAsyncationFilter继承时,有人想知道如何执行此操作

[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>();
}
[事实]
公共异步任务MyTest()
{
var modelState=new ModelStateDictionary();
var httpContextMock=新的DefaultHttpContext();
httpContextMock.Request.Query=new QueryCollection(新字典{});//如果您正在从查询参数读取任何属性
var actionContext=新的actionContext(
httpContextMock,
Mock.Of(),
Mock.Of(),
模型状态
);
var actionExecutingContext=新的actionExecutingContext(
行动背景,
新列表(),
新字典(),
模仿
)
{
Result=new-OkResult()//它将返回ok,除非在代码执行期间按条件更改此值
};
Mymock1.SetupGet(x=>x.SomeProperty).Returns(“MySomething”);
Mymock2.Setup(x=>x.GetSomething(It.IsAny(),It.IsAny()).ReturnsAsync(true);
var context=newactionExecutedContext(actionContext,new List(),Mock.Of());
wait _classUnderTest.OnActionExecutionAsync(actionExecutionContext,async()=>{return context;});
actionExecutingContext.Result.Should().BeOfType();
}
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: Microsoft.AspNet.Mvc.Filters.ActionExecutingContext.
      Could not find a constructor that would match given arguments:
      Microsoft.AspNet.Mvc.ActionContext
      Microsoft.AspNet.Mvc.Filters.IFilterMetadata[]
      System.Collections.Generic.Dictionary`2[System.String,System.Object]
[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>();
}