xunit Assert.NotNull() 不能很好地处理 C# 可空类型

发布于 2025-01-20 07:57:06 字数 655 浏览 3 评论 0 原文

Assert.NotNull(res);
Assert.Equal(1, res.Foo); // CS8602 warning here

我正在使用 xunit.assert 2.4.1、.NET 6.0、VS 2022。

当“Ctrl+Click”导航到 Assert.NotNull() 源代码 我可以看到它的定义是

public static void NotNull(object @object)

我实际上期望看到的

public static void NotNull([NotNull] object? @object)

从 xunit 源代码中可以看到,仅当 时才使用可空风格的方法XUNIT_NULLABLE 条件编译变量已启用。难道 nuget 下载了 xunit.assert 包的“不可为空”版本吗?我们如何强制使用“可空”版本(使用定义的 XUNIT_NULLABLE 构建)?

Assert.NotNull(res);
Assert.Equal(1, res.Foo); // CS8602 warning here

I'm using xunit.assert 2.4.1, .NET 6.0, VS 2022.

When "Ctrl+Click" navigating to the Assert.NotNull() source code I can see it defined as

public static void NotNull(object @object)

while I was actually expecting to see

public static void NotNull([NotNull] object? @object)

From the xunit source code one can see that nullable flavour of methods are used only when XUNIT_NULLABLE conditional compilation variable is enabled. Can it be that nuget downloaded "non-nullable" version of the xunit.assert package? How can we force a "nullable" version (built with the XUNIT_NULLABLE defined)?

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

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

发布评论

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

评论(1

澉约 2025-01-27 07:57:06

最后,Xunit 2.4.2已发布,并且essert.notnull()与C#无效类型效果很好!

以下代码是实现

        /// <summary>
        /// Verifies that an object reference is not null.
        /// </summary>
        /// <param name="object">The object to be validated</param>
        /// <exception cref="NotNullException">Thrown when the object reference is null</exception>
#if XUNIT_NULLABLE
        public static void NotNull([NotNull] object? @object)
#else
        public static void NotNull(object @object)
#endif
        {
            if (@object == null)
                throw new NotNullException();
        }

Finally, xunit 2.4.2 has been released and Assert.NotNull() plays nicely with C# nullable types!!

The following code is the implementation of NotNull method in xunit.assert 2.4.2.

        /// <summary>
        /// Verifies that an object reference is not null.
        /// </summary>
        /// <param name="object">The object to be validated</param>
        /// <exception cref="NotNullException">Thrown when the object reference is null</exception>
#if XUNIT_NULLABLE
        public static void NotNull([NotNull] object? @object)
#else
        public static void NotNull(object @object)
#endif
        {
            if (@object == null)
                throw new NotNullException();
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文