【问题标题】:xunit Assert.NotNull() does not play nicely with C# nullable typesxunit Assert.NotNull() 不能很好地处理 C# 可为空的类型
【发布时间】:2022-08-08 12:44:04
【问题描述】:
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 构建)?

  • 这与 XUnit 无关。 C# 编译器告诉您,此时该值仍然可以为空。
  • @scottdavidwalker,我想你误解了我的问题。 C# 编译器肯定会生成警告,但它这样做是因为Assert.NotNull() 不会阻止编译器发出警告。您可以创建自定义 NotNull() 方法 private void NotNull([NotNull] object? @object) {} 并使用它来使编译器静音,那么为什么 NUnit Assert.NotNull() 不能这样做呢?实际上它可以,请点击我在问题中分享的链接,也许你会得到我的问题。
  • 它是 v3 的一部分。 github.com/xunit/xunit/issues/2011 我认为 nuget 包是在没有设置标志的情况下编译的,所以我们还没有那个能力。

标签: xunit nullable-reference-types


【解决方案1】:

最后,xunit 2.4.2 已经发布并且 Assert.NotNull() 与 C# 可空类型很好地配合!!

以下代码是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();
        }

【讨论】:

    猜你喜欢
    • 2012-06-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    相关资源
    最近更新 更多