Skip to content

feat: suppress TUnit0046 (Func<T> warning) for record types #4770

@thomhurst

Description

@thomhurst

Problem

TUnit0046 warns that `[MethodDataSource]` methods should return `Func` for reference type parameters to ensure test isolation. This makes sense for mutable classes, but is unnecessary for record types which are immutable by design.

```csharp
// Records are immutable - no isolation concern
public record CreateProductRequest(string Name, string Category, decimal Price);

// TUnit0046 warning on this:
public static IEnumerable ValidProducts()
{
yield return new("Speaker", "electronics", 39.99m);
}

// Forced to write this instead:
public static IEnumerable<Func> ValidProducts()
{
yield return () => new("Speaker", "electronics", 39.99m);
}
```

The `Func` wrapper adds noise without any benefit for immutable types. In the CloudShop example, every single data source method needed this wrapping because all DTOs are records.

Proposed Change

The TUnit0046 analyzer should check if `T` is a record type. If so, suppress the warning since records are immutable and sharing instances between tests is safe.

Detection: records have a compiler-synthesized `$` method, or the analyzer can check for the `record` modifier on the type declaration.

Scope

  • Only suppress for `record` and `record struct` types
  • Keep the warning for regular `class` types (which may be mutable)
  • `string` is already excluded - records should get the same treatment

Context

Discovered while building the CloudShop Aspire + TUnit example (#4761). All 5 data source methods triggered this warning, all for immutable record types.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions