Skip to content

Roslyn analyzer + code fix: convert WebApplicationFactory<T> to TestWebApplicationFactory<T> #5596

@thomhurst

Description

@thomhurst

Problem

Users who inherit from Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory<T> directly silently lose:

  • Trace propagation (no traceparent/baggage on outgoing requests).
  • Per-test logging correlation.
  • TestContext.Current resolution inside request handlers.

There is no compile-time signal. Discussion #5479 is one of multiple reports rooted in this exact mistake.

Proposal

Extend the existing WebApplicationFactoryAccessAnalyzer (or add a sibling rule) in TUnit.AspNetCore.Analyzers that flags:

public class MyFactory : WebApplicationFactory<Program> // TUNITxxxx
{
}

with severity Warning (not Error — some users may have legitimate reasons), and a code fix that converts to:

public class MyFactory : TestWebApplicationFactory<Program>
{
}

The code fix should also offer the alternative wrapping pattern when the inheritance can't be changed (e.g. third-party base class):

var factory = new TracedWebApplicationFactory<Program>(existingFactory);

Considerations

  • Scope to test projects. Detect via IsTestProject-style heuristics: Microsoft.Testing.Platform reference, or namespace contains .Tests. Avoid false positives in production code.
  • Opt-out. Standard #pragma warning disable plus .editorconfig rule severity.
  • Documentation link in diagnostic. helpLinkUri pointing to the new Distributed Tracing page.
  • Diagnostic ID. Allocate next free TUNITxxxx in the analyzer table.

Related

Documentation

When this lands, update:

  • docs/docs/examples/aspnet.md — update the existing "Use TestWebApplicationFactory<T>" warning callout to mention the new analyzer and its diagnostic ID, so users understand the warning they'll see in the IDE.
  • docs/docs/guides/distributed-tracing.md — link the diagnostic ID from the "WebApplicationFactory without TUnit's wrapper" limitation entry.
  • Analyzer rules documentation (if a per-rule reference exists) — add an entry for the new TUNITxxxx ID.

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