我试图模拟我的控制器来测试模型状态是否无效,如果模型状态无效,单元测试基本上会返回400错误。 但模型状态在Model Binder的 BindModel ()方法中得到验证。 通过单元测试,我无法点击 BindModel ()方法。
我有一个通用的方法来模拟下面显示的Controller方法:
public static async Task<HttpResponseMessage> MockController<T,
TReturn>(
this T controller, Func<T, Task<TReturn>> func, string requestUri =
"http://tempuri.org", HttpMethod httpMethod = null) where T : ApiController
{
using (var request = new HttpRequestMessage(httpMethod ?? HttpMethod.Get, new Uri(requestUri)))
{
controller.Request = request;
var actionResult = await func.Invoke(controller);
// Create the response from the action result
if (typeof(IHttpActionResult).IsAssignableFrom(typeof(TReturn)))
{
return await ((IHttpActionResult)actionResult).ExecuteAsync(CancellationToken.None);
}
else
{
return await Task.FromResult(request.CreateResponse(actionResult));
}
}
}
以上方法如下所示:
param无效
param=new someclass
{
Data1=new List{"abc"}
};
var response = await controller.MockController(async c =>
{
actionResult = await c.PostData(param);
return actionResult;
});
Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
我应该在MockController方法中进行哪些更改来调用BindModel传递的控制器类的方法?
模型活页夹
public class MyModelBinderProvider : ModelBinderProvider
{
public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
{
return new MyModelBinder();
}
}
public class MyModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var requestJson = actionContext.Request.Content.ReadAsStringAsync().Result;
var domain = actionContext.ActionArguments["domain"].ToString();
try
{
var model = Configuration.Load(requestJson);
bindingContext.Model = model;
domain = Map.GetEntityName(domain.Replace('-', '_'));
var invalidReqFieldsDict = RequestValidator.Validate(domain, model);
if (invalidReqFieldsDict.Any())
{
var exceptionMessage = String.Join("", invalidReqFieldsDict);
bindingContext.ModelState.AddModelError(bindingContext.ModelName, exceptionMessage);
return false;
}
return true;
}
catch (JsonException e)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, e.Message);
return false;
}
}
}
非常感谢任何帮助! 感谢