C# 如何在没有访问器的情况下对派生的DataGridViewCell进行单元测试?
我正在为DataGridViewCell类编写单元测试(在VS2010中),该类看起来有点像:C# 如何在没有访问器的情况下对派生的DataGridViewCell进行单元测试?,c#,unit-testing,datagridview,mstest,accessor,C#,Unit Testing,Datagridview,Mstest,Accessor,我正在为DataGridViewCell类编写单元测试(在VS2010中),该类看起来有点像: public class MyCell : DataGridViewCell { protected override object GetFormattedValue(object value, int rowIndex, ref System.Windows.Forms.DataGridViewCellStyle cellStyle, System.Componen
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的refection工具检查了这一点)
显然,我可以绕过这一点,只使用访问器访问受保护的或私有的方法,但在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上找到了这些信息,其中解释了如果melike的答案出于某种原因不是一个选项,那么如何使用它
尽管melike的答案对我很有用,但我想我应该学习一下它是如何工作的,下面是一个示例测试,以防它对任何人都有帮助:
[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的一个明显的缺点是方法名仅存储为字符串,如果更改名称或方法签名,则更难维护