【问题标题】:How to unit test a derived DataGridViewCell without accessors?如何在没有访问器的情况下对派生的 DataGridViewCell 进行单元测试?
【发布时间】:2014-01-29 10:49:55
【问题描述】:

我正在为一个看起来有点像这样的 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 refection 工具检查了这一点)。

我显然可以绕过这一点,只使用访问器来访问受保护的或私有的方法,但访问器在 VS2012 之后已被弃用。

如何在不使用访问器的情况下对该逻辑进行单元测试?

【问题讨论】:

    标签: c# unit-testing datagridview mstest accessor


    【解决方案1】:

    既然要设置DataGridViewCellDataGridView 显然还有很多工作要做,你为什么不试试别的呢?

    首先,创建一个执行特殊格式的组件:

    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 实现中还有很多其他事情发生,否则测试它没有太大价值。

    【讨论】:

      【解决方案2】:

      我确实在 MSDN Upgrading Unit Tests from Visual Studio 2010 上找到了此信息,其中解释了如果由于某种原因无法选择 melike 的答案,则使用 PrivateObject

      尽管 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 的一个明显缺点是方法名称仅存储为字符串 - 如果您更改名称或方法签名,将难以维护。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-05
        • 2014-07-29
        • 2022-10-19
        • 1970-01-01
        • 1970-01-01
        • 2021-06-14
        • 2023-01-09
        相关资源
        最近更新 更多