单元测试方法参数的BindAttribute
本文关键字:BindAttribute 参数 测试方法 单元 | 更新日期: 2023-09-27 17:53:34
我希望编写单元测试来验证我的控制器,同时确保绑定属性正确设置。使用下面的方法结构,我如何确保单元测试只传递有效的字段?
public ActionResult AddItem([Bind(Include = "ID, Name, Foo, Bar")] ItemViewModel itemData)
{
if (ModelState.IsValid)
{
// Save and redirect
}
// Set Error Messages
// Rebuild object drop downs, etc.
itemData.AllowedFooValues = new List<Foo>();
return View(itemData);
}
更广泛的解释:我们的许多模型都有我们不想来回发送的允许值列表,因此我们在(ModelState)。IsValid == false)。为了确保这些都能正常工作,我们想要在适当的位置放置单元测试来断言列表被重建,但是在调用方法之前没有清除列表,测试是无效的。
我们正在使用来自这个SO答案的helper方法来确保模型被验证,然后我们的单元测试是这样的。
public void MyTest()
{
MyController controller = new MyController();
ActionResult result = controller.AddItem();
Assert.IsNotNull(result);
ViewResult viewResult = result as ViewResult;
Assert.IsNotNull(viewResult);
ItemViewModel itemData = viewResult.Model as ItemViewModel;
Assert.IsNotNull(recipe);
// Validate model, will fail due to null name
controller.ValidateViewModel<ItemViewModel, MyController>(itemData);
// Call controller action
result = controller.AddItem(itemData);
Assert.IsNotNull(result);
viewResult = result as ViewResult;
Assert.IsNotNull(viewResult);
itemData = viewResult.Model as ItemViewModel;
// Ensure list was rebuilt
Assert.IsNotNull(itemData.AllowedFooValues);
}
我可能误解了你说的话,但听起来你想要一些东西来确保你在测试中创建的模型在传递给你的控制器之前被过滤,以模拟MVC绑定,并防止你意外地编写一个测试,将信息传递给你的控制器在测试中,实际上永远不会被框架填充。
考虑到这一点,我假设您只对Include
成员集的Bind属性感兴趣。在这种情况下,您可以使用如下命令:
public static void PreBindModel<TViewModel, TController>(this TController controller,
TViewModel viewModel,
string operationName) {
foreach (var paramToAction in typeof(TController).GetMethod(operationName).GetParameters()) {
foreach (var bindAttribute in paramToAction.CustomAttributes.Where(x => x.AttributeType == typeof(BindAttribute))) {
string properties;
try {
properties = bindAttribute.NamedArguments.Where(x => x.MemberName == "Include").First().TypedValue.Value.ToString();
}
catch (InvalidOperationException) {
continue;
}
var propertyNames = properties.Split(',');
var propertiesToReset = typeof(TViewModel).GetProperties().Where(x => propertyNames.Contains(x.Name) == false);
foreach (var propertyToReset in propertiesToReset) {
propertyToReset.SetValue(viewModel, null);
}
}
}
}
在您像这样调用控制器操作之前,它将从单元测试中被调用:
controllerToTest.PreBindModel(model, "SomeMethod");
var result = controllerToTest.SomeMethod(model);
本质上,它所做的是遍历传递给给定控制器方法的每个参数,查找绑定属性。如果它找到一个绑定属性,那么它就会得到Include
列表,然后它重置viewModel
中没有提到的每个属性(本质上是取消绑定它)。
上面的代码可能需要一些调整,我没有做太多的MVC工作,所以我对属性和模型的使用做了一些假设。
以上代码的改进版本,使用BindAttribute本身进行过滤:
public static void PreBindModel<TViewModel, TController>(this TController controller, TViewModel viewModel, string operationName) {
foreach (var paramToAction in typeof(TController).GetMethod(operationName).GetParameters()) {
foreach (BindAttribute bindAttribute in paramToAction.GetCustomAttributes(true)) {//.Where(x => x.AttributeType == typeof(BindAttribute))) {
var propertiesToReset = typeof(TViewModel).GetProperties().Where(x => bindAttribute.IsPropertyAllowed(x.Name) == false);
foreach (var propertyToReset in propertiesToReset) {
propertyToReset.SetValue(viewModel, null);
}
}
}
}
根据Forsvarir提供的答案,我想出了这个作为我的最终实现。我删除了泛型以减少每次使用它时的类型,并将其放在我的测试的基类中。我还必须为具有相同名称但不同参数的多个方法做一些额外的工作(例如:Get与Post),这是通过所有方法的循环而不是GetMethod来解决的。
public static void PreBindModel(Controller controller, ViewModelBase viewModel, string operationName)
{
MethodInfo[] methods = controller.GetType().GetMethods();
foreach (MethodInfo currentMethod in methods)
{
if (currentMethod.Name.Equals(operationName))
{
bool foundParamAttribute = false;
foreach (ParameterInfo paramToAction in currentMethod.GetParameters())
{
object[] attributes = paramToAction.GetCustomAttributes(true);
foreach (object currentAttribute in attributes)
{
BindAttribute bindAttribute = currentAttribute as BindAttribute;
if (bindAttribute == null)
continue;
PropertyInfo[] allProperties = viewModel.GetType().GetProperties();
IEnumerable<PropertyInfo> propertiesToReset =
allProperties.Where(x => bindAttribute.IsPropertyAllowed(x.Name) == false);
foreach (PropertyInfo propertyToReset in propertiesToReset)
{
propertyToReset.SetValue(viewModel, null);
}
foundParamAttribute = true;
}
}
if (foundParamAttribute)
return;
}
}
}
总的来说,这成为一个非常干净和简单的解决方案,所以现在我的测试看起来像这样:
[TestMethod]
public void MyTest()
{
MyController controller = new MyController();
ActionResult result = controller.MyAddMethod();
Assert.IsNotNull(result);
ViewResult viewResult = result as ViewResult;
Assert.IsNotNull(viewResult);
MyDataType myDataObject = viewResult.Model as MyDataType;
Assert.IsNotNull(myDataObject);
ValidateViewModel(myController, myDataObject);
PreBindModel(controller, myDataObject, "MyAddMethod");
Assert.IsNull(myDataObject.FieldThatShouldBeReset);
result = controller.MyAddMethod(myDataObject);
Assert.IsNotNull(result);
viewResult = result as ViewResult;
Assert.IsNotNull(viewResult);
myDataObject = viewResult.Model as MyDataType;
Assert.IsNotNull(myDataObject.FieldThatShouldBeReset);
}
作为参考,我的ValidateViewModel方法是:
public static void ValidateViewModel(BaseAuthorizedController controller, ViewModelBase viewModelToValidate)
{
var validationContext = new ValidationContext(viewModelToValidate, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(viewModelToValidate, validationContext, validationResults, true);
foreach (var validationResult in validationResults)
{
controller.ModelState.AddModelError(validationResult.MemberNames.FirstOrDefault() ?? string.Empty, validationResult.ErrorMessage);
}
}