[英]Unit Test and attribute
I have the following attribute: 我具有以下属性:
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ActionArguments["model"] == null)
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, new HttpError("Model is null") { { "CustomErrorCode", "480" } });
if (!actionContext.ModelState.IsValid)
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
//base.OnActionExecuting(actionContext);
}
}
and the WebAPI method: 和WebAPI方法:
[HttpPost]
[ValidateModel]
public async Task<HttpResponseMessage> SignUpAsync(ApiModels.RegisterAsSmartphonePhotographerApiModel model)
{
....
}
It work as expected, but when I want to write Unit Test: 它可以按预期工作,但是当我要编写单元测试时:
[TestMethod]
public async Task SignUp_InvalidModelState()
{
ApiModels.RegisterAsSmartphonePhotographerApiModel model1 = new ApiModels.RegisterAsSmartphonePhotographerApiModel()
{
Username = "abc"
};
HttpResponseMessage result1 = await controller.SignUpAsync(model1);
Assert.IsFalse(result1.IsSuccessStatusCode);
Assert.IsInstanceOfType(result1, typeof(BadRequestResult));
}
I get an exception because ValidateModelAttribute is not called. 我收到异常,因为未调用ValidateModelAttribute。 How can I "include" ValidateModel validation to unit test? 如何“包含” ValidateModel验证以进行单元测试?
You should test ValidateModelAttribute by itself. 您应该自己测试ValidateModelAttribute。 How it works when you decorate/annotate your method in the controller should be the frameworks responsibility. 在控制器中装饰/注释方法时,其工作方式应由框架负责。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.