Edit on GitHub

xUnit1045   v2 v3   Info

Avoid using TheoryData type arguments that might not be serializable

Cause

A violation of this rule occurs when a type in the generic TheoryData<> might not be serializable.

Reason for rule

Non-serializable data makes it impossible for the developer to run individual data rows inside of Visual Studio’s Test Explorer.

How to fix violations

To fix a violation of this rule, use data that is known to be serializable. This includes all the supported built-in types (listed below) or any type which implements IXunitSerializable, as well as arrays of any supported type and nullable versions of any supported value type. A type might or might not be serializable if it’s an interface (that does not derive from IXunitSerializable) or an unsealed class or struct (that does not implement IXunitSerializable).

Developers using xUnit.net v3 0.6.0 or later can also implement an external serializer by implementing IXunitSerializer and registering it in their test assembly. For more information, see the v3 documentation on custom serialization.

Supported built-in types for v2 (as of 2.7.1) and v3 include:

Additional built-in types supported for v3 (as of 0.5.0) include:

Examples

Violates

using System;
using Xunit;

public class TestClass
{
    public static TheoryData<IDisposable> DataSource = [];

    [Theory]
    [MemberData(nameof(DataSource))]
    public void TestMethod(IDisposable disposable) { }
}

Does not violate

using System;
using Xunit;
using Xunit.Abstractions;  // for IXunitSerializable in v2
using Xunit.Sdk;           // for IXunitSerializable in v3

public interface IDisposableSerializable : IDisposable, IXunitSerializable { }

public class TestClass
{
    public static TheoryData<IDisposableSerializable> DataSource = [];

    [Theory]
    [MemberData(nameof(DataSource))]
    public void TestMethod(IDisposableSerializable disposable) { }
}
Copyright © .NET Foundation. Contributions welcomed at https://github.com/xunit/xunit/tree/gh-pages.