Skip to content

fix(mocks): preserve nullable base-class constraints - #7829

Merged
thomhurst merged 1 commit into
mainfrom
fix/7820-nullable-base-class-constraints
Nov 19, 2026
Merged

thomhurst merged 1 commit into
mainfrom
fix/7820-nullable-base-class-constraints

Conversation

@thomhurst

@thomhurst thomhurst commented Nov 19, 2026 •

Copy link
Copy Markdown
Owner

Description

Generic mock methods returning or accepting T? failed to compile when T had a base-class constraint. For example, Task<(T? act, string error)> ActFromInvoice<T>() where T : BaseAct, new() generated an explicit forward without where T : class, causing CS0453, CS9334, and CS0535.

Record Roslyn's semantic IsReferenceType classification separately from the explicit class constraint and use it when formatting explicit implementations. Ordinary declarations retain their full original constraints, and interface-only or unconstrained parameters retain default handling.

Related Issue

Fixes #7820

Type of Change

  • Bug fix (non-breaking change that fixes an issue)

Checklist

  • Read the contributing guidelines and followed the existing code style.
  • Added regressions that fail before the fix: five constraint rows failed while eight control rows passed.
  • Reviewed and committed the new snapshot and the one-line change to the existing nullable-constraint snapshot.
  • Included the semantic flag in model equality and hashing for incremental generation.

Testing

Both affected suites pass on net10.0 and net11.0 with SDK 11.0.100:

  • dotnet test --project tests/TUnit.Mocks.SourceGenerator.Tests --framework <framework>: 254 passed per framework.
  • dotnet test --project tests/TUnit.Mocks.Tests --framework <framework>: 1,542 passed per framework.

New coverage includes:

  • Thirteen constraint combinations across nullable returns, nested task/tuple returns, arrays, parameters, and ref/out parameters.
  • Mixed and transitive constraints across multiple type parameters.
  • Inherited and hidden interface slots, source and metadata declarations, and class-primary multi-interface mocks.
  • Four runtime cases using the reported static mock syntax, verifying setup, null/non-null results, nullable type arguments, and dispatch through both the wrapper and Object.

The generator test compiler predates C# 14, so compilation guards exclude diagnostics from static-extension convenience files only. Runtime tests compile the complete generated output with the SDK.

Additional Notes

This changes mock source generation; it adds no runtime reflection or public library API. Existing build warnings remain tracked in #7410, #7412, and #7828.

Summary by CodeRabbit

  • Bug Fixes
    • Generated mocks now preserve reference-type constraints on explicit interface implementations, improving compatibility with nullable generic method signatures.
    • Mock setup and verification now work correctly for nullable tuple returns, nullable parameters and return values, and nullable array type arguments.
    • Generic methods with multiple or inherited constraints now retain their individual constraints in generated mocks.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T17:37:31.683081Z ef944c7 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The source generator now carries reference-type usage into type-parameter models and emits the corresponding class constraint on explicit-interface implementations. New tests check generated compilation and nullable mock setup and verification.

Changes: Nullable Generic Constraint Generation

Layer / File(s) Summary
Record reference-type usage
src/TUnit.Mocks.SourceGenerator/Models/MockTypeParameterModel.cs, src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs, src/TUnit.Mocks.SourceGenerator/Discovery/MockTypeDiscovery.cs
Type-parameter models now store IsReferenceType. Equality and hash-code calculations include this property.
Emit and validate explicit-interface constraints
src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs, tests/TUnit.Mocks.SourceGenerator.Tests/Issue7820Tests.cs, tests/TUnit.Mocks.SourceGenerator.Tests/Snapshots/*
The generator emits where T : class for explicit-interface type parameters with reference-type usage. Tests and snapshots cover nullable signatures, constraint forms, inheritance, and generated mocks.
Test nullable mock setup and verification
tests/TUnit.Mocks.Tests/Issue7820Tests.cs
Tests configure and verify nullable tuple returns, nullable values and parameters, and nullable array type arguments through the mock wrapper and its Object.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Minimal · up to ef944

This change makes generated mocks compile for generic methods returning nullable T when T has a base-class constraint. It is source-generation-only, has regression coverage, and I found no concrete merge-blocking risk.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "fix(mocks): preserve nullable base-class constraints" matches the main change. The PR changes how the source generator formats explicit-interface generic constraints for type parameters wit…
Linked Issues check Passed [#7820] requires that generated mocks compile for interface methods returning T? when T has a base-class constraint, with the explicit implementation carrying the needed nullability constraint. At the…
Out of Scope Changes check Passed All changes support the #7820 fix. The MockImplBuilder change is the core fix. The MemberDiscovery, MockTypeDiscovery, and MockTypeParameterModel changes carry the IsReferenceType classification neede…
Full details: Title check

Explanation

The title "fix(mocks): preserve nullable base-class constraints" matches the main change. The PR changes how the source generator formats explicit-interface generic constraints for type parameters with reference-type usage, so nullable T? with a base-class constraint keeps the required class constraint. The linked issue #7820 and the objectives describe the same problem. The title is short, specific, and uses a conventional commit prefix.

Full details: Linked Issues check

Explanation

[#7820] requires that generated mocks compile for interface methods returning T? when T has a base-class constraint, with the explicit implementation carrying the needed nullability constraint. At the reviewed head, MockImplBuilder.FormatConstraintClauses emits 'where T : class' for explicit implementations when tp.IsReferenceType is true, replacing the earlier check on HasReferenceTypeConstraint only. This covers base-class constraints, which the issue identifies as the missing case. MemberDiscovery and MockTypeDiscovery populate MockTypeParameterModel.IsReferenceType from Roslyn, and the model includes it in equality and hashing. The new Issue7820Tests cover base-class constrained nullable returns, nested task and tuple returns, and multiple type parameters. Runtime tests in TUnit.Mocks.Tests exercise the reported syntax. The change only touches the explicit-implementation branch, so ordinary declarations keep their full constraints. The author reports passing test suites on net10.0 and net11.0. I did not run the suites. Based on the diff and the reported results, the requirement is met.

Full details: Out of Scope Changes check

Explanation

All changes support the #7820 fix. The MockImplBuilder change is the core fix. The MemberDiscovery, MockTypeDiscovery, and MockTypeParameterModel changes carry the IsReferenceType classification needed by that fix. The Generic_Constraints_Preserve_Nullability snapshot change is a one-line update that follows from emitting 'class' on the explicit implementation. The new Issue7820Tests in both test projects and the generated snapshot files are regression coverage for the fix. No change is unrelated to #7820 or to its supporting test coverage.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks each type constraint,
And finds the class clause in its place.
Nullable calls now compile clean,
With tuples and arrays in the scene.
The mock returns what tests expect,
Then counts each call with care.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5a321422-8a67-4d02-b649-9e1eb25bf837
Commits

Reviewing files that changed from the base of the PR and between d4c0670 and ef944c7.

Files selected for processing: 8

  • src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs
  • src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs
  • src/TUnit.Mocks.SourceGenerator/Discovery/MockTypeDiscovery.cs
  • src/TUnit.Mocks.SourceGenerator/Models/MockTypeParameterModel.cs
  • tests/TUnit.Mocks.SourceGenerator.Tests/Issue7820Tests.cs
  • tests/TUnit.Mocks.SourceGenerator.Tests/Snapshots/Base_Class_Constrained_Nullable_Generic_Methods.verified.txt
  • tests/TUnit.Mocks.SourceGenerator.Tests/Snapshots/Generic_Constraints_Preserve_Nullability.verified.txt
  • tests/TUnit.Mocks.Tests/Issue7820Tests.cs

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

@github-actions

Copy link
Copy Markdown
Contributor

Review of #7829

The change is small and targeted, and I found nothing that needs fixing.

  • Fix: MockImplBuilder now keys the explicit-implementation where T : class off Roslyn's semantic IsReferenceType instead of only the syntactic HasReferenceTypeConstraint. This fixes the CS0453/CS9334/CS0535 errors for T? with a base-class constraint. Ordinary declarations keep their full original constraints.
  • Incremental generation: the new flag is included in MockTypeParameterModel equality and hashing. It is populated in both MemberDiscovery and MockTypeDiscovery, so the metadata and source paths behave the same.
  • Tests: the 13-row constraint matrix, the multi-type-parameter cases, the inherited/hidden slots, the metadata-reference variants and the runtime cases cover the risky combinations well. The compile check filters out the _MockStaticExtension file because the pinned Roslyn predates C# 14 extension blocks. That is a reasonable workaround, and the comment explains it.
  • Snapshots: the one-line change to the existing Base<T> snapshot (it now gets where T : class) is expected and legal.

One optional follow-up: add a test for a type parameter constrained to another reference-type parameter (for example T : U where U : class). Find<T,U> covers part of this already, so it is not blocking.

I read the diff and did not run the tests. LGTM.

@greptile-apps

greptile-apps Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] This PR appears safe to merge; no actionable issues were found.

Summary

This PR fixes generated mock methods that use nullable generic values with base-class constraints.

  • Generated mock forwards keep nullable generic methods compilable.

No actionable issues found. Tests were inspected but not run during this review.

Reviews (1) · Last reviewed commit: "fix(mocks): preserve nullable base-class..." · Reviewed by Greptile

@thomhurst
thomhurst enabled auto-merge (squash) November 19, 2026 17:45
@thomhurst
thomhurst merged commit 3353473 into main Nov 19, 2026
27 checks passed
@thomhurst
thomhurst deleted the fix/7820-nullable-base-class-constraints branch November 19, 2026 18:00
This was referenced Nov 20, 2026

This branch was previously deployed

1 inactive deployment
Pull Requests — ef944c7a Deployed Nov 19, 2026 by thomhurst via modularpipeline (windows-latest) #21784
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.

[Bug]: TUnit.Mocks: explicit implementation of a generic method returning T? with a base-class constraint lacks 'where T : class' (CS0453/CS9334/CS0535)

1 participant