Skip to content

Migrate NetAnalyzers tests from xUnit to MSTest - #55066

Merged
Evangelink merged 5 commits into
mainfrom
dev/amauryleve/netanalyzers-xunit-to-mstest
Jun 30, 2026
Merged

Evangelink merged 5 commits into
mainfrom
dev/amauryleve/netanalyzers-xunit-to-mstest

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Summary

Migrates the src/Microsoft.CodeAnalysis.NetAnalyzers/tests suite (~7,000 [Fact] + ~950 [Theory] across ~400 files) off xUnit and onto MSTest v4 (MSTest.Sdk), so the tree contains zero functional xUnit test-framework references. This is one of several parallel xUnit-removal efforts; the change is strictly scoped to the tests/ tree.

Projects

  • Test.Utilities → MSTest.Sdk with IsTestApplication=false (Core MSTest.TestFramework reference only). Dropped xunit.v3.assert and Xunit.Combinatorial.
  • Microsoft.CodeAnalysis.NetAnalyzers.UnitTests → MSTest.Sdk. Dropped the (unused, xUnit-coupled) Microsoft.NET.TestFramework project reference; added Combinatorial.MSTest.
  • TestReferenceAssembly — added a tiny Xunit.Sdk.NamespaceCollisionMarker type (see below).

Mechanical conversions (string/comment-aware, so attributes inside analyzed test-source strings were left untouched)

  • [Fact]/[Theory] → [TestMethod]; [InlineData] → [DataRow]; [MemberData]/[ClassData] → [DynamicData]; [Trait] → [TestProperty]
  • [Fact/Theory(Skip="…")] → [TestMethod] + [Ignore("…")]; per-row [InlineData(…, Skip=…)] (4 rows) commented out (MSTest has no per-row skip)
  • [WindowsOnlyFact] (from Microsoft.DotNet.XUnitV3Extensions) → [TestMethod] + [OSCondition(OperatingSystems.Windows)]
  • Assert.* → MSTest equivalents (Assert.AreEqual, Assert.IsTrue, Assert.ThrowsExactly<T>, Assert.IsEmpty, Assert.Fail, …)
  • Added [TestClass] to every test class (including concrete classes that only inherit test methods from abstract bases); made static/internal test methods instance/public
  • Removed using Xunit; everywhere it was real code
  • Replaced xUnit's TheoryData<…> with a small MSTest-friendly shim in Test.Utilities that implements IEnumerable<object[]> (consumable by [DynamicData])

How the verifier / CancellationToken was handled

The shared verifier wrappers and ~230 test files called test.RunAsync(Xunit.TestContext.Current.CancellationToken) (xUnit v3's ambient token). MSTest has no static ambient equivalent inside these static helpers, so every occurrence was replaced with CancellationToken.None. All using Xunit; lines were removed from Test.Utilities; the framework-agnostic Microsoft.CodeAnalysis.*.Testing (DefaultVerifier) references are unchanged.

Two notable judgement calls

  • WorkItemAttribute collision — MSTest ships its own WorkItemAttribute(int), which collides with the repo's Test.Utilities.WorkItemAttribute(int, string). Rather than touch 124 files, a single global alias <Using Include="Test.Utilities.WorkItemAttribute" Alias="WorkItemAttribute" /> makes the unqualified [WorkItem(id, "url")] usages bind to the repo's attribute.
  • CA1724 tests — TypeNamesShouldNotMatchNamespacesTests referenced typeof(Xunit.Sdk.AllException) purely to contribute an Xunit.Sdk namespace to the analyzed compilation. Replaced with a new Xunit.Sdk.NamespaceCollisionMarker defined in TestReferenceAssembly, so the real xunit package is no longer needed.

Parallelization

Preserved the suite's existing serial execution: xUnit ran with parallelizeTestCollections: false, and MSTest.Sdk here emits [assembly: DoNotParallelize] (via the repo's MSTestParallelizeScope=None).

Validation

Both projects build clean (0 warnings, 0 errors) with the repo SDK. Ran representative subsets under MTP — all green:

  • AvoidEmptyInterfaces (53), TypeNamesShouldNotMatchNamespaces (16, validates the CA1724 marker), DoNotCallEnumerableCast… (16, Assert.ThrowsExactly), PreferIsEmptyOverCount (119, ClassData→DynamicData), DoNotUseCountWhenAnyCanBeUsed (664, TheoryData/DynamicData), UseConcreteType (52, de-static classes), UseDefaultDllImportSearchPathsAttribute (56, OSCondition), AvoidDeadConditionalCode (235, Combinatorial.MSTest).

grep -ri xunit src/Microsoft.CodeAnalysis.NetAnalyzers/tests shows only incidental references: xUnit-as-analyzed-code test data (AdditionalMetadataReferences.DefaultWithXUnit, which adds the xunit NuGet package as reference assemblies for the code-under-analysis), the Xunit.Sdk.NamespaceCollisionMarker, and [Fact]/using Xunit; text embedded inside analyzed-source string literals — none of which are the test framework.

Co-authored-by: Copilot [email protected]

Evangelink and others added 2 commits June 30, 2026 08:38
Switch Test.Utilities and TestReferenceAssembly off xUnit:
- Test.Utilities -> MSTest.Sdk (IsTestApplication=false), drop xunit.v3.assert/Xunit.Combinatorial
- Verifier wrappers: remove using Xunit; TestContext.Current.CancellationToken -> CancellationToken.None
- Add MSTest-friendly TheoryData shim replacing xUnit's TheoryData
- CodeMetricsTestsBase: Assert.* -> MSTest equivalents (Assert.Fail/IsEmpty)
- TestReferenceAssembly: add Xunit.Sdk.NamespaceCollisionMarker so CA1724 tests no longer need the real xunit assembly

Co-authored-by: Copilot <[email protected]>
Mechanical xUnit -> MSTest conversion across ~380 test files:
- [Fact]/[Theory] -> [TestMethod]; [InlineData] -> [DataRow]; [MemberData]/[ClassData] -> [DynamicData]
- [Trait] -> [TestProperty]; [Fact/Theory(Skip)] -> [TestMethod]+[Ignore]; [WindowsOnlyFact] -> [TestMethod]+[OSCondition(Windows)]
- Assert.* -> MSTest equivalents (Assert.ThrowsExactly etc.); TestContext.Current.CancellationToken -> CancellationToken.None
- Add [TestClass] to every test class (incl. inherited-test derived classes); make static/internal test methods instance/public
- Project -> MSTest.Sdk; drop Microsoft.NET.TestFramework ref; add Combinatorial.MSTest; alias WorkItemAttribute to Test.Utilities'

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings June 30, 2026 06:39
@Evangelink
Evangelink requested a review from a team as a code owner June 30, 2026 06:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review this pull request because it exceeds the maximum number of files (300). Try reducing the number of changed files and requesting a review from Copilot again.

Evangelink and others added 3 commits June 30, 2026 09:57
…e string

The migration's 'add using Test.Utilities;' helper was line-based and inserted the using after the last top-level using directive in the file. In DoNotCallToImmutableCollectionOnAnImmutableCollectionValueTests.Fixer.cs that last match was a 'using' line INSIDE the interpolated verbatim 'expected' fixed-code baseline string, corrupting the expected output and failing CA2009_Arity2_CSharpAsync for ImmutableDictionary/ImmutableSortedDictionary. Removed the stray line so expected matches the analyzer's actual fix output.

Co-authored-by: Copilot <[email protected]>
@Evangelink

Copy link
Copy Markdown
Member Author

CI status: NetAnalyzers migration is green — remaining red is unrelated macOS-arm64 infra flakiness

The one real test failure this PR introduced (CA2009_Arity2_CSharpAsync for ImmutableDictionary/ImmutableSortedDictionary) was a migration artifact — a using Test.Utilities; line accidentally injected into an expected fixed-code baseline string. Fixed in 58d486b. Since then the NetAnalyzers tests pass on every platform; the only CI red is unrelated macOS-arm64 agent flakiness in test suites this PR does not touch.

Evidence (this PR only changes src/Microsoft.CodeAnalysis.NetAnalyzers/tests/**):

Build NetAnalyzers result Remaining failure(s) macOS-arm64 agent
1487277 (pre-fix) ❌ 4 NetAnalyzers work items (the real bug) — —
1487369 (post-fix) ✅ 0 failures (linux-x64 14086/0, windows-x64 14373/0, FullFramework 14490/0) dotnet.Tests, Microsoft.NET.Build.Tests, dotnet-new.IntegrationTests, StaticWebAssets.Tests, Web.Tests c6ec5108
1487539 (re-run) ✅ 0 failures (incl. macOS-arm64 TestBuild 13870/0, linux-x64 14086/0) Microsoft.NET.Sdk.BlazorWebAssembly.AoT.Tests e3b6ccf5

Different unrelated suites failing each run, only on macOS-arm64, on different agents (c6ec5108 vs e3b6ccf5), all with exit code 2 and no published test results = a host-level macOS-arm64 infra problem in dnceng-public, not a test regression. A PR touching only NetAnalyzers tests cannot affect Blazor AoT / dotnet.Tests / Build.Tests.

This is repo-wide, not PR-specific: the latest main CI build (1486966) is also red with the same macOS failures across many assemblies — including Microsoft.CodeAnalysis.NetAnalyzers.UnitTests.dll.11 on macOS, which on main is still the old xUnit suite (so macOS fails NetAnalyzers even without this change).

Plan: no code changes for these — they are out of this PR's scope. Once the macOS-arm64 queue recovers we'll do one clean re-run for a fully green build; if the infra flakiness persists, we'll ask the dnceng owners to classify it as a known infra issue rather than chase unrelated suites.

@Evangelink

Copy link
Copy Markdown
Member Author

/ba-g #51530

@Evangelink

Copy link
Copy Markdown
Member Author

Verdict for reviewers/mergers: migration validated — only red is macOS-arm64 infra flakiness

TL;DR: The NetAnalyzers xUnit→MSTest migration is correct and green on all platforms. The one real regression it introduced is fixed. The remaining CI red is unrelated macOS-arm64 infrastructure flakiness that also affects main.

(a) The one real failure — root cause & fix

The initial run failed CA2009_Arity2_CSharpAsync for ImmutableDictionary/ImmutableSortedDictionary. Root cause: the migration's "add using Test.Utilities;" helper was line-based and inserted the directive after the file's last top-level using — which in DoNotCallToImmutableCollectionOnAnImmutableCollectionValueTests.Fixer.cs was a using line inside the interpolated expected fixed-code baseline string, corrupting the expected output. Fixed in 58d486b by removing that stray line. Verified locally 12/12 pass, deterministic across 3 runs. A repo-wide string/comment-aware scan confirmed this was the only such occurrence.

(b) Before/after CI evidence (this PR only touches src/Microsoft.CodeAnalysis.NetAnalyzers/tests/**)

Build NetAnalyzers result
1487277 (pre-fix) ❌ 4 NetAnalyzers work-item failures (the CA2009 bug)
1487369 (post-fix) ✅ 0 NetAnalyzers failures; all 4 TestBuild jobs succeeded — linux-x64 14086/0, windows-x64 14373/0, FullFramework 14490/0
1487539 (re-run) ✅ 0 NetAnalyzers failures; incl. macOS-arm64 TestBuild 13870/0, linux-x64 14086/0, windows-x64 14373/0

(c) The remaining red is macOS-arm64 infra, not this PR

The only failures across the post-fix runs are unrelated suites on macOS-arm64, with exit code 2 and no published test results (host-crash signature), on different agents each run:

  • 1487369: dotnet.Tests, Microsoft.NET.Build.Tests, dotnet-new.IntegrationTests, Microsoft.NET.Sdk.StaticWebAssets.Tests, Microsoft.NET.Sdk.Web.Tests — agent c6ec5108
  • 1487539: Microsoft.NET.Sdk.BlazorWebAssembly.AoT.Tests — agent e3b6ccf5

A PR touching only NetAnalyzers tests cannot affect Blazor AoT / dotnet.Tests / Build.Tests. Different unrelated suites, only on macOS-arm64, on different agents each run = a host-level macOS-arm64 problem in dnceng-public. Confirmation it's repo-wide and not this PR: the latest main CI build (1486966) is also red with the same macOS failures across many assemblies — including Microsoft.CodeAnalysis.NetAnalyzers.UnitTests.dll.11 on macOS, which on main is still the old xUnit suite (so macOS fails NetAnalyzers even without this change).

Recommendation

The migration is complete and green on its own merits. The remaining red is external macOS-arm64 infra flakiness (also red on main). Suggest merge-on-merits, or wait for the macOS-arm64 pool to recover / a known-issue classification — no code changes in this PR are warranted for those unrelated suites.

@Evangelink
Evangelink merged commit f20699e into main Jun 30, 2026
23 of 25 checks passed
@Evangelink
Evangelink deleted the dev/amauryleve/netanalyzers-xunit-to-mstest branch June 30, 2026 17:00
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-preview7 milestone Jul 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants