我正在为 WPF 应用程序编写(尝试编写)单元测试。
UI 绑定以实现 IDataErrorInfo 的业务对象,这样当我在 View xaml 中设置 ValidatesOnDataErrors=True 时,只要调用绑定业务对象的设置器,就会调用错误索引器 (this[])。那部分很棒。
现在,如果我从 unitTest 调用相同属性的设置器,它永远不会调用错误索引器。如何强制从单元测试中评估 IDataErrorInfo 索引器?
只是为了说明,这是我的一个简单的错误索引器,它包含一个 Name 属性。设置'myObject.Name = string.Empty;' 当我在单元测试中这样做时,确实调用了设置器,但不调用错误索引器。
public string Name
{
get { return _name; }
set
{
_name = value;
IsDirty = true;
OnPropertyChanged("Name");
}
}
#region IDataErrorInfo
public Dictionary<string, string> ErrorCollection;
public string this[string property]
{
get
{
string msg = null;
switch (property)
{
case "Name":
if (string.IsNullOrEmpty(Name))
msg = "ICU Name is required.";
else if (Name.Length < 4)
msg = "ICU Name must contain at least 4 characters.";
else if (_parent.Units.AsEnumerable().Count(u => u.Name == Name) > 1)
msg = Name + " already exists, please change to a different Name.";
break;
}
if (msg != null && !ErrorCollection.ContainsKey(property))
ErrorCollection.Add(property, msg);
if (msg == null && ErrorCollection.ContainsKey(property))
ErrorCollection.Remove(property);
return msg;
}
}
public string Error
{
get { return null; }
}
#endregion
谢谢!