2016-03-08 198 views
0

我有以下屬性:單元測試和屬性

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

和的WebAPI方法:

 [HttpPost] 
     [ValidateModel] 
     public async Task<HttpResponseMessage> SignUpAsync(ApiModels.RegisterAsSmartphonePhotographerApiModel model) 
     { 
.... 
     } 

它工作正常,但是當我想編寫單元測試:

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

我得到一個異常,因爲沒有調用ValidateModelAttribute。我如何「包括」ValidateModel驗證單元測試?

+1

我會按照[this](http://stackoverflow.com/a/8508700/502395)的回答分別測試'ValidateModelAttribute'。 – venerik

回答

0

您應該自己測試ValidateModelAttribute。當您在控制器中修飾/註釋您的方法時,它的工作原理應該是框架的責任。