Skip to content

[duplicate-code] Duplicate Code: ClassInitialize/ClassCleanup AnalyzeSymbol Pattern in Fixture Analyzers #9490

Closed

Description

Analysis of commit a80cd31

Assignee: @copilot

Summary

ClassInitializeShouldBeValidAnalyzer and ClassCleanupShouldBeValidAnalyzer contain near-identical AnalyzeSymbol methods (~13–16 lines each). This duplication mirrors the pattern that was just refactored for TestInitializeShouldBeValidAnalyzer / TestCleanupShouldBeValidAnalyzer in PR #9485 (commit a80cd31), which introduced FixtureMethodAnalyzerHelper.RegisterInstanceFixtureAnalyzer. The class-level equivalents were not updated and remain duplicated.

Duplication Details

Pattern: Near-identical class-level fixture AnalyzeSymbol methods

  • Severity: Medium
  • Occurrences: 2 instances
  • Locations:
    • src/Analyzers/MSTest.Analyzers/ClassInitializeShouldBeValidAnalyzer.cs (lines 46–61)
    • src/Analyzers/MSTest.Analyzers/ClassCleanupShouldBeValidAnalyzer.cs (lines 44–61)

ClassInitializeShouldBeValidAnalyzer.AnalyzeSymbol:

private static void AnalyzeSymbol(SymbolAnalysisContext context, FixtureMethodAnalyzerHelper.FixtureMethodSymbols symbols)
{
    var methodSymbol = (IMethodSymbol)context.Symbol;
    bool isInheritanceModeSet = methodSymbol.IsInheritanceModeSet(symbols.InheritanceBehaviorSymbol, symbols.FixtureAttributeSymbol);
    if (methodSymbol.HasAttribute(symbols.FixtureAttributeSymbol)
        && ((!methodSymbol.HasValidFixtureMethodSignature(symbols.TaskSymbol, symbols.ValueTaskSymbol, symbols.CanDiscoverInternals, shouldBeStatic: true,
            allowGenericType: isInheritanceModeSet, FixtureParameterMode.MustHaveTestContext, symbols.TestContextSymbol,
            symbols.TestClassAttributeSymbol, fixtureAllowInheritedTestClass: true, out bool isFixable))
            || (!isInheritanceModeSet && methodSymbol.ContainingType.IsAbstract)
            || (isInheritanceModeSet && methodSymbol.ContainingType.IsSealed)))
    {
        context.ReportDiagnostic(isFixable
            ? methodSymbol.CreateDiagnostic(Rule, methodSymbol.Name)
            : methodSymbol.CreateDiagnostic(Rule, DiagnosticDescriptorHelper.CannotFixProperties, methodSymbol.Name));
    }
}

ClassCleanupShouldBeValidAnalyzer.AnalyzeSymbol: identical structure, only FixtureParameterMode.OptionalTestContext differs from FixtureParameterMode.MustHaveTestContext.

Impact Analysis

  • Maintainability: Any future change to class-fixture validation logic (e.g., adding a new rule about abstract/sealed type handling) must be applied to both files independently, risking drift — exactly the drift risk that motivated the PR Refactor TestInitialize/TestCleanup analyzer registration into shared fixture helper #9485 refactoring for instance fixtures.
  • Bug Risk: High — the two files are currently in sync, but a fix in one may not be propagated to the other.
  • Code Bloat: ~16 lines of functionally duplicated code across 2 files.

Refactoring Recommendations

  1. Add RegisterClassFixtureAnalyzer helper to FixtureMethodAnalyzerHelper (analogous to RegisterInstanceFixtureAnalyzer)
    • Extract the common logic into:
      internal static void RegisterClassFixtureAnalyzer(
          AnalysisContext context,
          string fixtureAttributeMetadataName,
          DiagnosticDescriptor rule,
          FixtureParameterMode parameterMode)
          => RegisterFixtureMethodSymbolAction(
              context,
              fixtureAttributeMetadataName,
              static (symbolContext, symbols, state) => AnalyzeClassFixtureMethod(symbolContext, symbols, state.rule, state.parameterMode),
              (rule, parameterMode),
              requireTestContextSymbol: parameterMode == FixtureParameterMode.MustHaveTestContext);
    • Add the shared AnalyzeClassFixtureMethod private method:
      internal static void AnalyzeClassFixtureMethod(
          SymbolAnalysisContext context,
          FixtureMethodSymbols symbols,
          DiagnosticDescriptor rule,
          FixtureParameterMode parameterMode)
      {
          var methodSymbol = (IMethodSymbol)context.Symbol;
          bool isInheritanceModeSet = methodSymbol.IsInheritanceModeSet(symbols.InheritanceBehaviorSymbol, symbols.FixtureAttributeSymbol);
          if (methodSymbol.HasAttribute(symbols.FixtureAttributeSymbol)
              && ((!methodSymbol.HasValidFixtureMethodSignature(symbols.TaskSymbol, symbols.ValueTaskSymbol,
                  symbols.CanDiscoverInternals, shouldBeStatic: true,
                  allowGenericType: isInheritanceModeSet, parameterMode, symbols.TestContextSymbol,
                  symbols.TestClassAttributeSymbol, fixtureAllowInheritedTestClass: true, out bool isFixable))
                  || (!isInheritanceModeSet && methodSymbol.ContainingType.IsAbstract)
                  || (isInheritanceModeSet && methodSymbol.ContainingType.IsSealed)))
          {
              context.ReportDiagnostic(isFixable
                  ? methodSymbol.CreateDiagnostic(rule, methodSymbol.Name)
                  : methodSymbol.CreateDiagnostic(rule, DiagnosticDescriptorHelper.CannotFixProperties, methodSymbol.Name));
          }
      }
    • Update ClassInitializeShouldBeValidAnalyzer.Initialize to:
      FixtureMethodAnalyzerHelper.RegisterClassFixtureAnalyzer(
          context,
          WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingClassInitializeAttribute,
          Rule,
          FixtureParameterMode.MustHaveTestContext);
    • Remove the private AnalyzeSymbol method from both analyzers.
    • Estimated effort: ~1 hour
    • Benefits: Centralizes class-fixture validation logic; prevents drift; consistent with PR Refactor TestInitialize/TestCleanup analyzer registration into shared fixture helper #9485 pattern.

Implementation Checklist

  • Review duplication findings
  • Add AnalyzeClassFixtureMethod and RegisterClassFixtureAnalyzer to src/Analyzers/MSTest.Analyzers/Helpers/FixtureMethodAnalyzerHelper.cs
  • Update ClassInitializeShouldBeValidAnalyzer.Initialize to delegate to the new helper
  • Update ClassCleanupShouldBeValidAnalyzer.Initialize to delegate to the new helper
  • Remove private AnalyzeSymbol methods from both analyzer classes
  • Verify analyzer tests still pass
  • Verify no functionality broken

Analysis Metadata

  • Analyzed Files: ClassInitializeShouldBeValidAnalyzer.cs, ClassCleanupShouldBeValidAnalyzer.cs, FixtureMethodAnalyzerHelper.cs
  • Detection Method: Semantic code analysis — structural similarity following the TestInitialize/TestCleanup refactoring
  • Commit: a80cd31
  • Analysis Date: 2026-06-29

🤖 Automated content by GitHub Copilot. Posted via a maintainer's GitHub token, so it appears under their account — the account owner did not write or approve this content personally. Generated by the Duplicate Code Detector workflow. · 530.8 AIC · ⌖ 25 AIC · ⊞ 43.6K · [◷]( · ◷)

Add this agentic workflows to your repo

To install this agentic workflow, run

gh aw add githubnext/agentics/workflows/duplicate-code-detector.md@main
  • expires on Jul 1, 2026, 5:57 AM UTC

Activity

  1. added
    type/tech-debt
    type/automation
    on Jun 29, 2026
  2. Evangelink commented on Jun 29, 2026

    @Evangelink
    MemberAuthor

    This was resolved by #9492 (Refactor duplicated class fixture analyzer validation into shared helper), which is merged into main.

    ClassInitializeShouldBeValidAnalyzer and ClassCleanupShouldBeValidAnalyzer now delegate to FixtureMethodAnalyzerHelper.RegisterClassFixtureAnalyzer and the private AnalyzeSymbol methods were removed.

    The analyzed duplication is no longer present in the codebase, so closing as completed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

type/automationtype/tech-debt

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions