为 VS UT Assert 类创建自定义扩展方法的最佳方法是什么?

发布于 2024-11-29 03:36:54 字数 68 浏览 2 评论 0原文

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

I would like to know what is the best way to write custom extensions methods for Microsoft Visual Studio Unit Testing Assert class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只是偏爱你 2024-12-06 03:36:54

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

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);

You can create extension methods for this Assert class.

The version of class Assert is now as:

public sealed class Assert
{
    private static Assert that;

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

Which means now you can create extension methods for the Assert class.

For example you can have the extension method:

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..");
        }
    }
}

And then on unit tests you can make:

Assert.That.IsDateToday(someDateTime);
浅浅 2024-12-06 03:36:54

如果您引用此 Assert 类,则无法添加扩展方法。扩展方法只能应用于对象实例。由于此类是静态的,因此永远无法实例化它。

您可以添加自己的自定义 Assert 类型类,如下所示:

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

If you are referring to this Assert class, then you cannot add extension methods. Extension methods can only be applied to object instances. Since this class is static, it can never be instantiated.

You could add your own custom Assert type class like so though:

public static class MyAssert {
    public static void AreEqual(object expected, object actual) {
        // TODO: throw if not equal
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文