Skip to content

Conversation

Copilot
Copy link
Contributor

@Copilot Copilot AI commented Aug 13, 2025

The hook metadata generator was failing when processing abstract base classes that have parameterized constructors and hook methods. This resulted in a NullReferenceException during test discovery.

Problem

The issue occurred when:

  1. An abstract base class has a parameterized constructor (which is automatically protected)
  2. The abstract class contains hook methods like [Before(Test)]
  3. A concrete class inherits from this abstract base class

The WriteClassMetadataGetOrAdd method in MetadataGenerationHelper.cs was calling typeSymbol.InstanceConstructors.FirstOrDefault() which returns any instance constructor, including protected ones. For abstract classes with parameterized constructors, this would select a protected constructor and later cause issues during metadata generation.

Example that previously failed

public abstract class BaseTestClass(IServiceProvider serviceProvider)
{
    [Before(Test)]
    public Task Hook() => Task.CompletedTask;
}

[ClassConstructor<DependencyInjectionClassConstructor>]
public sealed class ActualTestClass(IServiceProvider serviceProvider)
    : BaseTestClass(serviceProvider)
{
    [Test]
    public void Test1() { }
}

This would throw:

System.TypeInitializationException: The type initializer for 'TUnit.Generated.Hooks.GeneratedHookRegistry' threw an exception.
---> System.InvalidOperationException: Failed to initialize hook registry: Object reference not set to an instance of an object.
---> System.NullReferenceException: Object reference not set to an instance of an object.

Solution

Modified the constructor selection logic in MetadataGenerationHelper.cs to:

  1. Skip constructor processing entirely for abstract classes - Since abstract classes cannot be instantiated directly, their constructor metadata is not needed for the testing framework
  2. Only consider public constructors for concrete classes - This ensures we don't accidentally process protected or private constructors

The fix maintains backward compatibility while properly handling abstract inheritance patterns commonly used with dependency injection.

Testing

  • Added reproduction test case that matches the original issue report
  • Verified existing abstract class tests (like BaseClass<T>) continue to work
  • Confirmed PublicAPI tests pass without changes
  • Validated that the build succeeds without the previous null reference exception

Fixes #2887.

Warning

Firewall rules blocked me from connecting to one or more addresses

I tried to connect to the following addresses, but was blocked by firewall rules:

  • aka.ms
    • Triggering command: curl -I -sSL --retry 5 --retry-delay 2 --connect-timeout 15 REDACTED (dns block)

If you need me to access, download, or install something from one of these locations, you can either:


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Co-authored-by: thomhurst <30480171+thomhurst@users.noreply.github.com>
@Copilot Copilot AI changed the title [WIP] Abstract Class [Before(Test)] breakage Fix abstract class constructor processing in hook metadata generation Aug 13, 2025
@Copilot Copilot AI requested a review from thomhurst August 13, 2025 19:05
Copilot finished work on behalf of thomhurst August 13, 2025 19:05
@thomhurst thomhurst marked this pull request as ready for review August 13, 2025 19:12
@thomhurst thomhurst enabled auto-merge (squash) August 13, 2025 19:19
Copy link
Contributor

claude bot commented Aug 13, 2025

Claude finished @Copilot's task —— View job


Code Review Complete ✅

Todo List:

  • Read repository guidelines (CLAUDE.md) - No CLAUDE.md found
  • Analyze the core fix in MetadataGenerationHelper.cs
  • Review test coverage and reproduction cases
  • Examine code quality and best practices
  • Check for potential bugs or issues
  • Assess performance and security considerations
  • Provide comprehensive feedback

📋 Review Summary

This PR provides an excellent fix for issue #2887. The solution is well-designed, thoroughly tested, and maintains backward compatibility.

Strengths

Code Quality

  • Surgical precision: The fix is minimal and targeted, modifying only the essential logic in MetadataGenerationHelper.cs:149-154
  • Clear intent: The conditional logic with descriptive comments makes the solution easy to understand
  • Consistent patterns: Uses existing codebase conventions and maintains the same approach in both method variants

Problem Resolution

  • Root cause addressed: Correctly identifies that abstract classes cannot be instantiated and skips their constructor processing
  • Defensive programming: The fix prevents future similar issues by explicitly handling abstract class scenarios
  • Logical correctness: Only processes public constructors for concrete classes, which aligns with testing framework requirements

Test Coverage

  • Comprehensive reproduction: ReproTest.cs exactly matches the failing scenario from the issue
  • Verification test: Issue2887Tests.cs ensures the fix works without generation errors
  • Generated output validation: The .verified.txt file shows correct metadata generation for the concrete class

💡 Minor Observations

Code Organization

The fix appears in two places due to method duplication:

  • WriteClassMetadataGetOrAdd() (lines 149-154) - newer method
  • GenerateClassMetadataGetOrAdd() (lines 217-222) - legacy method for backward compatibility

This is actually good practice as it maintains consistency across both code paths.

Performance Considerations

  • Efficient early exit: Skipping abstract class processing reduces unnecessary work
  • Minimal overhead: The IsAbstract check is a simple property access
  • No new allocations: The fix doesn't introduce additional memory usage

🔒 Security Assessment

  • No security concerns: The changes are limited to metadata generation logic
  • Access control maintained: Constructor accessibility filtering remains proper
  • No external dependencies: The fix uses existing framework APIs

🎯 Test Strategy Evaluation

The testing approach is solid:

  1. Reproduction test: Validates the exact failing scenario
  2. Source generation test: Ensures generated code compiles and runs
  3. Regression prevention: The verified output serves as a snapshot test

📊 Overall Assessment

This is a high-quality fix that:

  • Solves the immediate problem effectively
  • Maintains backward compatibility
  • Includes comprehensive test coverage
  • Uses minimal, targeted changes
  • Follows existing code patterns

Recommendation: ✅ Approve

The fix is ready to merge. It addresses the root cause, includes proper testing, and maintains code quality standards.


This was referenced Aug 20, 2025
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.

Abstract Class [Before(Test)] breakage
2 participants