自定义验证器属性在单元测试中起作用,但在Web api控制器中不起作用?

时间:2018-09-10 14:54:30

标签: c# data-annotations asp.net-core-webapi asp.net-core-webapi-2.1

ValidateMinMaxListCountAttribute验证属性在我的单元测试中有效,但在Web api框架中使用时不起作用?

例如,在单元测试中,“ isValid”返回true,但在控制器中失败。我正在猜测某种序列化问题?

有人有什么想法吗?

[TestCategory("ServiceTests")]
[TestMethod]
public void CallServiceCalc()
{

    var client = new RestClient();
    client.BaseUrl = new Uri("https://localhost:44379");
    client.Authenticator = new HttpBasicAuthenticator("eric.schneider", "password");

    var request = new RestRequest();
    request.Resource = "api/Calculation/Calculate";

    CoralRequest coralReq = new CoralRequest();
    coralReq.ModelId = 1;
    coralReq.ModelName = "2018";
    coralReq.BasePlan = new BeneifitsPlanInputs();
    coralReq.Plans.Add(new BeneifitsPlanInputs());
    request.AddBody(coralReq);

    ValidateMinMaxListCountAttribute va = new ValidateMinMaxListCountAttribute(1, 999);
    bool isValid = va.IsValid(coralReq.Plans);

    IRestResponse response = client.Execute(request);

    Assert.IsTrue(response.StatusCode == System.Net.HttpStatusCode.OK, "Should not be ok");
}

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ValidateMinMaxListCountAttribute : ValidationAttribute
{
    public ValidateMinMaxListCountAttribute(int minimum, int maximum)

{
    this.MinimumCount = minimum;
    this.MaximumCount = maximum;
}

public int MinimumCount { get; set; }
public int MaximumCount { get; set; }

public override bool IsValid(object value)
{
    var list = value as ICollection;

    if (list != null)
    {
        if (list.Count > MaximumCount) { return false; }
        if (list.Count < MinimumCount) { return false; }
        return true;
        }

        return false;
    }
}


   public class CoralRequest
    {
        public CoralRequest()

    {
        this.Plans = new List<BeneifitsPlanInputs>();
    }


    /// <summary>
    /// 
    /// </summary>
    [ValidateMinMaxListCount(1, 99, ErrorMessage = "Must have between 1 and 99 plans")]
    public IList<BeneifitsPlanInputs> Plans { get; set; }
}

1 个答案:

答案 0 :(得分:1)

根据您似乎与之相关的其他问题之一,您表明控制器动作看起来像...

[HttpGet("{mock}")]
public ActionResult<CoralResult> CalculateMock(CoralRequest mock)

在测试中,正在发出GET请求,但GET请求没有BODY,但是您向请求中添加了一个。这意味着最有可能在服务器上未正确填充/绑定模型

这看起来像经典的XY problem

如果您想获取请求的主体,则该操作很可能应该是POST请求,并且应重构该操作以明确说明应从何处获取数据。

[Route("api/[controller]")]
public class CalculationController: Controller {

    //POST api/Calculation/Calculate
    [HttpPost("[action]")]
    public ActionResult<CoralResult> Calculate([FromBody]CoralRequest model) {
        if(ModelState.IsValid) {
            CoralResult result = new CoralResult();

            //...do something with model and populate result.

            return result;
        }
        return BadRequest(ModelState);
    }

}

现在哪个应该与集成测试中尝试的更匹配

[TestCategory("ServiceTests")]
[TestMethod]
public void CallServiceCalc() {

    var client = new RestClient();
    client.BaseUrl = new Uri("https://localhost:44379");
    client.Authenticator = new HttpBasicAuthenticator("eric.schneider", "password");

    var request = new RestRequest(Method.POST); //<-- POST request
    request.Resource = "api/Calculation/Calculate";
    request.AddHeader("content-type", "application/json");

    CoralRequest coralReq = new CoralRequest();
    coralReq.ModelId = 1;
    coralReq.ModelName = "2018";
    coralReq.BasePlan = new BeneifitsPlanInputs();
    coralReq.Plans.Add(new BeneifitsPlanInputs());
    request.AddJsonBody(coralReq); //<-- adding data as JSON to body of request

    IRestResponse response = client.Execute(request);

    Assert.IsTrue(response.StatusCode == System.Net.HttpStatusCode.OK, "Should be HttpStatusCode.OK");
}

在绑定模型并将其传递给操作之后,模型绑定器现在应该能够验证模型。

引用Model Binding in ASP.NET Core