[英]How to unit test a derived DataGridViewCell without accessors?
我正在为一个看起来像这样的DataGridViewCell类编写单元测试(在VS2010中):
public class MyCell : DataGridViewCell
{
protected override object GetFormattedValue(object value, int rowIndex, ref System.Windows.Forms.DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter valueTypeConverter, System.ComponentModel.TypeConverter formattedValueTypeConverter, System.Windows.Forms.DataGridViewDataErrorContexts context)
{
return MyCustomFormatting(value);
}
private object MyCustomFormatting(object value)
{
var formattedValue = string.Empty;
// ... logic to test here
return FormattedValue;
}
}
我想测试公共属性.FormattedValue是否正确设置。 但是,如果要测试的单元未设置DataGridView,则此方法始终返回null(我使用Telerik的JustDecompile复制工具进行了检查)。
我显然可以绕过此操作,而仅使用访问器来访问受保护的方法或私有方法,但是从VS2012起不推荐使用访问器。
如何在不使用访问器的情况下对该逻辑进行单元测试?
既然显然要设置DataGridViewCell
和DataGridView
有很多工作要做,为什么不尝试其他方法呢?
首先,创建一个执行特殊格式的组件:
public class SpecialFormatter
{
public object Format(object value)
{
var formattedValue = string.Empty;
// ... logic to test here
return FormattedValue;
}
}
然后将其用于您的DataGridViewCell
实现:
public class MyCell : DataGridViewCell
{
protected override object GetFormattedValue(object value, int rowIndex, ref System.Windows.Forms.DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter valueTypeConverter, System.ComponentModel.TypeConverter formattedValueTypeConverter, System.Windows.Forms.DataGridViewDataErrorContexts context)
{
return MyCustomFormatting(value);
}
private object MyCustomFormatting(object value)
{
return new SpecialFormatter.Format(value);
}
}
然后,继续进行SpecialFormatter
单元测试,就可以完成了。 除非您的DataGridViewCell
实现中发生了很多其他事情,否则对其进行测试没有太多价值。
我发现在MSDN此信息升级单元测试从Visual Studio 2010在那里它解释了如何使用PrivateObject如果茅的答案是不是出于某种原因的选项。
即使我喜欢的答案对我有用,我还是想学习一下它是如何工作的,这是一个示例测试,以防它对任何人有帮助:
[TestMethod]
public void MyCellExampleTest()
{
var target = new MyCell();
var targetPrivateObject = new PrivateObject(target);
var result = targetPrivateObject.Invoke("MyCustomFormatting", new object[] { "Test" });
Assert.AreEqual(string.Empty, result);
}
使用PrivateObject的一个明显的缺点是方法名称只是存储为字符串-如果更改名称或方法签名,将很难维护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.