小编Kau*_*ano的帖子

单元测试自定义验证过滤器

我有以下属性:

public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }  
Run Code Online (Sandbox Code Playgroud)

我有这个通用的扩展方法,用于确定属性是否应用于方法

public static bool ActionHasFilter(this ApiController controller, string action, Type filter)
    {
        var controllerType = controller.GetType();
        var method = controllerType.GetMethod(action);

        object[] filters = method.GetCustomAttributes(filter, true);

        return filters.Any(x=>x.GetType() == filter);

    }
Run Code Online (Sandbox Code Playgroud)

我的问题是如何在不测试控制器动作的情况下测试属性是否真实有效?

假设我有以下实体

public class UserViewModel
{
     [Required]
     public string Name {get; set;}
     [Required]
     [EmailAddress]
     public string Email {get;set;
}
Run Code Online (Sandbox Code Playgroud)

我将如何模拟上下文并检查模型是否有效?

我正在使用Nunit和Moq.

nunit unit-testing moq asp.net-web-api

4
推荐指数
1
解决办法
3381
查看次数

标签 统计

asp.net-web-api ×1

moq ×1

nunit ×1

unit-testing ×1