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

时间:2018-05-21 10:54:40

标签: c# wpf xaml converters

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

转换器的代码是:

   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();
        }
    }

我该如何开始?

2 个答案:

答案 0 :(得分:2)

昨天我尝试了类似的东西,但是我没有字体,所以也许这会帮助你TestCaseSourceAttribute

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

答案 1 :(得分:1)

  

我该如何开始?

  1. 将单元测试项目(.NET Framework)添加到您的解决方案中。 (新项目 - >已安装 - > Visual C# - >在Visual Studio中进行测试)。
  2. 添加对新创建单元测试项目中定义BirdEyeViewColumnWidthConverter的项目的引用。项目 - >添加参考 - >项目 - >解决方案。
  3. 在生成的TestMethod1()类的UnitTest1中重命名并编写单元测试。
  4. 在此方法中,您将创建转换器类的实例,调用其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);
        }
    }