gpt4 book ai didi

unit-testing - 对自定义验证过滤器进行单元测试

转载 作者:行者123 更新时间:2023-12-04 04:17:56 26 4
gpt4 key购买 nike

我有以下属性:

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

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

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);

}

我的问题是如何在不测试 Controller 操作的情况下测试属性是否真正起作用?

假设我有以下实体

public class UserViewModel
{
[Required]
public string Name {get; set;}
[Required]
[EmailAddress]
public string Email {get;set;
}

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

我正在使用 Nunit 和 Moq。

最佳答案

Spock's solution是在正确的轨道上,但对代码有点过于侵入,因为它使 ValidateModelAttribute依赖于 TestableHttpActionContext 的类.我的实现使用了一个公共(public)属性,该属性将用于“注入(inject)”Request单元测试的对象,而作为属性的实现继续使用 Request来自 ActionContext 的对象:

public class ValidateModelAttribute : ActionFilterAttribute
{
public HttpRequestMessage TestRequestMessage { get; set; }

public override void OnActionExecuting(HttpActionContext actionContext)
{
PerformValidation(actionContext, TestRequestMessage ?? actionContext.Request);
}

private void PerformValidation(HttpActionContext actionContext, HttpRequestMessage request)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}

单元测试:
[Test]
public void OnActionExecuting_ValidModel_ResponseIsNotSet()
{
var actionContext = new HttpActionContext();

actionContext.ModelState.Clear();

var attribute = new ValidateModelAttribute { TestRequestMessage = new HttpRequestMessage() };

attribute.OnActionExecuting(actionContext);

Assert.IsNull(actionContext.Response);
}

[Test]
public void OnActionExecuting_InvalidModel_ResponseIsSetToBadRequest()
{
var actionContext = new HttpActionContext();

actionContext.ModelState.AddModelError("key", "error");

var attribute = new ValidateModelAttribute() { TestRequestMessage = new HttpRequestMessage() };

attribute.OnActionExecuting(actionContext);

Assert.AreEqual(HttpStatusCode.BadRequest, actionContext.Response.StatusCode);
}

请注意,我没有使用实际模型来验证 ModelState ,因为这超出了单元测试的范围:我们要测试 ModelState的结果,而不是 ModelState本身。 ;-)

关于unit-testing - 对自定义验证过滤器进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27124478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com