我在我的项目中定义了一个转换器。我想首先为该转换器编写单元测试用例。
转换器的代码是:
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();
}
}
我该如何开始?
答案 0 :(得分:2)
昨天我尝试了类似的东西,但是我没有字体,所以也许这会帮助你TestCaseSourceAttribute
此外,当你实现参数时,检查返回的类型是否与你期望的相同 - 例如Assert.IsInstanceOf(typeof(DateTime), obj.CreationTime);
答案 1 :(得分:1)
我该如何开始?
BirdEyeViewColumnWidthConverter
的项目的引用。项目 - >添加参考 - >项目 - >解决方案。TestMethod1()
类的UnitTest1
中重命名并编写单元测试。 在此方法中,您将创建转换器类的实例,调用其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);
}
}