首页 > 解决方案 > xUnit 测试通过但得到“灾难性失败:System.ArgumentException”

问题描述

当使用 xunit 在 .net 5.0 项目中从命令行 ( dotnet test) 运行测试时,所有测试似乎都通过了,但进程崩溃并出现以下详细信息dotnet test

Catastrophic failure: System.ArgumentException : There is at least one object in this array that cannot be serialized (Parameter 'array')
[xUnit.net 00:00:03.74]     [FATAL ERROR] System.ArgumentException
[xUnit.net 00:00:03.74]       System.ArgumentException : There is at least one object in this array that cannot be serialized (Parameter 'array')
[xUnit.net 00:00:03.74]       Stack Trace:
[xUnit.net 00:00:03.74]         C:\Dev\xunit\xunit\src\xunit.runner.utility\Extensions\MessageSinkMessageExtensions.cs(44,0): at MessageSinkMessageExtensions.Dispatch[TMessage](IMessageSinkMessage message, HashSet`1 messageTypes, MessageHandler`1 callback)

这只是dotnet test在从命令行运行时发生,从 VisualStudio 运行测试有效。

我正在使用TestServer.

任何想法可能是什么原因?

使用的软件包版本:

<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="5.0.8" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.10.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">

- 更新 -

我只是意识到这里描述的错误是在使用以以下示例类作为参数的 xUnit Theory 时发生的:

    public record TruncatedString
    {
        public TruncatedString(string value)
        {
            Value = FormatTruncatedString(value);
        }

        protected string Value { get; }

        protected static string FormatTruncatedString(string value)
        {
            return value.Substring(0,4);
        }

        public static implicit operator string(TruncatedString truncated) => truncated.Value;
        public static implicit operator TruncatedString(string text) => new (text);

        public override string ToString() => Value;
    }

并且在这样的 xUnit Theory 中使用:

[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("ABC")]
public async Task ThestWithTheErrorMessage(TruncatedString value)
{
    // ...
    // THIS TEST PRODUCE THE SERIALIZATION ERROR
    // System.ArgumentException : There is at least one object in this array that cannot be serialized (Parameter 'array')
    //   Stack Trace:
    //     C:\Dev\xunit\xunit\src\xunit.runner.utility\Extensions\MessageSinkMessageExtensions.cs(39,0): at MessageSinkMessageExtensions.Dispatch[TMessage](IMessageSinkMessage message, HashSet`1 messageTypes, MessageHandler`1 callback)
}

标签: .net-corexunitdotnet-cli

解决方案


I've run into the same issue. It seems that xUnit will not run the theory test if there's an implicit conversion happening.

Rewrite your test to be like:

[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("ABC")]
public async Task Test(string input)
{
    TruncatedString value = input;
    // ...
}

This bug in xUnit is documented here: https://github.com/xunit/xunit/issues/1742


推荐阅读