【问题标题】:What is the best way to create custom extension methods for VS UT Assert class?为 VS UT Assert 类创建自定义扩展方法的最佳方法是什么?
【发布时间】:2020-04-01 16:29:07
【问题描述】:

我想知道为 Microsoft Visual Studio 单元测试 Assert 类编写自定义扩展方法的最佳方式。

【问题讨论】:

标签: c# unit-testing visual-studio-2008 mstest


【解决方案1】:

如果你指的是这个Assert 类,那么你不能添加扩展方法。扩展方法只能应用于对象实例。由于这个类是静态的,它永远不能被实例化。

您可以像这样添加自己的自定义 Assert 类型类:

public static class MyAssert {
    public static void AreEqual(object expected, object actual) {
        // TODO: throw if not equal
    }
}

【讨论】:

    【解决方案2】:

    您可以为此Assert 类创建扩展方法。

    Assert 类的版本现在为:

    public sealed class Assert
    {
        private static Assert that;
    
        public static Assert That
        {
            get
            {
                if (Assert.that == null)
                    Assert.that = new Assert();
                return Assert.that;
            }
        }
    }
    

    这意味着您现在可以为 Assert 类创建扩展方法。

    例如你可以有扩展方法:

    public static class AssertExtensions
    {
        public static void IsDateToday(this Assert assert, DateTime today)
        {
            if (today.Date != DateTime.Now.Date)
            {
                throw new AssertFailedException("Kaboom! Assert failed bro..");
            }
        }
    }
    

    然后你可以进行单元测试:

    Assert.That.IsDateToday(someDateTime);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-15
      • 2014-01-29
      • 2015-12-11
      • 2019-11-28
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多