测试DependencyProperty.UnsetValue相等性总是失败,如何正确验证?
我实现了如下转换器,其ConvertBack方法返回DependencyProperty.UnsetValue:
public class DictionaryValueConverter<T> : IValueConverter { ... public object ConvertBack( object value, Type targetType, object parameter, string language) { return DependencyProperty.UnsetValue; } }
在单元测试中对返回值进行断言时,所有断言均失败:
Assert.Same() Failure: Values are not the same instance
Expected: IInspectable { ObjRef = ObjectReference1 { ThisPtr = 1754526379632, Vftbl = WinRT.IInspectable+Vftbl }, ThisPtr = 1754526379632 } Actual: IInspectable { ObjRef = ObjectReference1 { ThisPtr = 1754526385520, Vftbl = WinRT.IInspectable+Vftbl }, ThisPtr = 1754526385520 }
Assert.Equal() Failure: Values differ
Expected: IInspectable { ObjRef = ObjectReference1 { ThisPtr = 2602783527936, Vftbl = WinRT.IInspectable+Vftbl }, ThisPtr = 2602783527936 } Actual: IInspectable { ObjRef = ObjectReference1 { ThisPtr = 2602783529856, Vftbl = WinRT.IInspectable+Vftbl }, ThisPtr = 2602783529856 }
我尝试了多种断言方式均无效,期望能够验证返回结果确实是DependencyProperty.UnsetValue,请问该如何实现?
问题核心是DependencyProperty.UnsetValue在WinRT环境下每次访问都会生成新的IInspectable包装实例,导致引用比较(Assert.Same)和默认值比较失效。正确的验证方式是利用其重写的Equals方法:
// 方式1:调用UnsetValue的Equals方法直接判断 Assert.True(DependencyProperty.UnsetValue.Equals(converter.ConvertBack(yourTestValue, typeof(T), null, string.Empty))); // 方式2:使用Object.Equals静态方法 Assert.True(Object.Equals(DependencyProperty.UnsetValue, converter.ConvertBack(yourTestValue, typeof(T), null, string.Empty))); // 方式3:若使用xUnit,可指定默认相等比较器 Assert.Equal(DependencyProperty.UnsetValue, converter.ConvertBack(yourTestValue, typeof(T), null, string.Empty), EqualityComparer<object>.Default);
DependencyProperty.UnsetValue的Equals方法已经针对WinRT包装场景做了特殊处理,能正确识别不同实例背后代表的是同一个特殊值,避开包装层的干扰。
内容的提问来源于stack exchange,提问作者Abdessattar

