wpf 中转换器的单元测试用例

unit test cases for converters in wpf

我在我的项目中定义了一个转换器。我想开始为该转换器编写单元测试用例。

转换器代码为:

   public class BirdEyeViewColumnWidthConverter : IValueConverter
    {
        public int BirdEyeModeWidth { get; set; }
        public int DefaultWidth { get; set; }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                if ((bool) value)
                {
                    return BirdEyeModeWidth;
                }
            }
            return DefaultWidth;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

我该如何开始呢?

昨天我尝试了类似的东西,但我用的不是对象而是字典,所以也许这会对你有所帮助

此外,当您实现参数时,请检查返回类型是否与您期望的类型相同 - 例如Assert.IsInstanceOf(typeof(DateTime), obj.CreationTime);

How do I start with this?

  1. 将单元测试项目 (.NET Framework) 添加到您的解决方案中。 (新建项目->已安装->Visual C#->在 Visual Studio 中测试)。
  2. 在新创建的单元测试项目中添加对 BirdEyeViewColumnWidthConverter 定义的项目的引用。项目->添加引用->项目->解决方案。
  3. 在生成的UnitTest1class的TestMethod1()中重命名并编写单元测试。

在此方法中,您创建转换器 class 的实例,调用其 Convert 方法并断言返回值是您期望的值,例如

[TestClass]
public class BirdEyeViewColumnWidthConverterTests
{
    [TestMethod]
    public void BirdEyeViewColumnWidthConverterTest()
    {
        const int BirdEyeModeWidth = 20;
        const int DefaultWidth = 10;

        BirdEyeViewColumnWidthConverter converter = new BirdEyeViewColumnWidthConverter()
        {
            BirdEyeModeWidth = BirdEyeModeWidth,
            DefaultWidth = DefaultWidth,
        };

        int convertedValue = (int)converter.Convert(true, typeof(int), null, CultureInfo.InvariantCulture);
        Assert.AreEqual(BirdEyeModeWidth, convertedValue);

        convertedValue = (int)converter.Convert(false, typeof(int), null, CultureInfo.InvariantCulture);
        Assert.AreEqual(DefaultWidth, convertedValue);
    }
}