GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(mocks): bind explicit method type arguments on Mock.Of<IGeneric<X>>() by thomhurst · Pull Request #7406 · thomhurst/TUnit

fix(mocks): bind explicit method type arguments on Mock.Of<IGeneric<X>>() #7406

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
thomhurst merged 6 commits into main from issue-7302-generic-explicit-typeargs
Nov 3, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

fix(mocks): bind explicit method type arguments on Mock.Of<IGeneric<X>>() #7406

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit Hold shift + click to select a range
588f759
fix(mocks): bind explicit method type arguments on Mock.Of<IGeneric<X…
thomhurst Nov 2, 2026
9877a64
fix(mocks): omit colliding closed setup overloads (#7302)
thomhurst Nov 2, 2026
8741dd5
fix(mocks): normalize closed signatures without recursive substitutio…
thomhurst Nov 2, 2026
f46bdb2
docs(mocks): explain emitted signature collision checks (#7302)
thomhurst Nov 3, 2026
0df9256
docs(mocks): link setup emitter to collision analysis (#7302)
thomhurst Nov 3, 2026
360a7ca
fix(mocks): guard closed setup analysis against emitter drift (#7302)
thomhurst Nov 3, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

6 changes: 6 additions & 0 deletions 6 docs/docs/writing-tests/mocking/advanced.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,12 @@ If the closed type is only known at runtime, for example `Mock.Of<IRepository<T>

The built-in `DefaultValueProvider` uses reflection to build defaults for `Task<T>`, `ValueTask<T>`, and collection types, so it is not AOT-safe. A custom `IDefaultValueProvider` that does not use reflection works under Native AOT.

### Generic Methods on Generic Interfaces

A generic method on a generic interface can be set up with explicit type arguments, such as `mock.Invoke<string>(Any())`, on both `IOutbox<int>.Mock()` and `Mock.Of<IOutbox<int>>()`. On `Mock<T>`, this works for closed types named in `Mock.Of<T>()`, `MockRepository.Of<T>()`, or `[assembly: GenerateMock(typeof(IOutbox<int>))]`.

A few methods still need `IOutbox<int>.Mock()` for explicit type arguments: those with a constraint that names an interface type parameter, such as `TOther Select<TOther>() where TOther : T`, and those that use an unconstrained interface type parameter as `T?`. When C# can infer the type arguments from the call, as in `mock.RoundTrip(Arg.Any<Guid>())`, every form works.

## Reset

Clear all setups, call history, state, and auto-tracked property values. Configuration such as `Behavior`, `DefaultValueProvider` and `PassThrough` is kept:
Expand Down
109 changes: 99 additions & 10 deletions 109 src/TUnit.Mocks.SourceGenerator/Builders/ClosedGenericRegistrationBuilder.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Globalization;
using System.Collections.Immutable;
using TUnit.Mocks.SourceGenerator.Models;

Expand All @@ -11,6 +12,7 @@ namespace TUnit.Mocks.SourceGenerator.Builders;
internal static class ClosedGenericRegistrationBuilder
{
public const string HintName = "TUnit.Mocks.ClosedGenericFactories.g.cs";
public const string MethodSetupsHintName = "TUnit.Mocks.ClosedGenericMethodSetups.g.cs";

public static string Build(EquatableArray<ClosedGenericFactoryEmission> registrations)
{
Expand Down Expand Up @@ -45,18 +47,112 @@ public static string Build(EquatableArray<ClosedGenericFactoryEmission> registra
return writer.ToString();
}

/// <summary>
/// Pairs each distinct registration with the closed factory of the open mock generated for it.
/// </summary>
public static EquatableArray<ClosedGenericFactoryEmission> Resolve(
ImmutableArray<ClosedGenericMockRegistration> registrations,
ImmutableArray<MockTypeModel> models)
{
var emissions = new List<ClosedGenericFactoryEmission>();
foreach (var (registration, model) in Pair(registrations, models))
{
emissions.Add(new ClosedGenericFactoryEmission(
registration.ClosedTypeFullyQualifiedName,
$"{MockImplBuilder.GetGlobalMockNamespacePrefix(model)}{MockImplBuilder.GetCompositeShortSafeName(model)}MockFactory.CreateAutoMock<{string.Join(", ", registration.TypeArguments)}>"));
}

// Ordinal order keeps the emitted file stable regardless of call-site discovery order.
emissions.Sort(static (x, y) => StringComparer.Ordinal.Compare(x.ClosedTypeFullyQualifiedName, y.ClosedTypeFullyQualifiedName));
return new EquatableArray<ClosedGenericFactoryEmission>(emissions.ToImmutableArray());
}

/// <summary>
/// Pairs each distinct registration with the open mock generated for it, keeping only mocks with
/// generic methods whose setups need a closed receiver to accept explicit type arguments (#7302).
/// </summary>
public static EquatableArray<ClosedGenericMethodSetupEmission> ResolveMethodSetups(
ImmutableArray<ClosedGenericMockRegistration> registrations,
ImmutableArray<MockTypeModel> models)
{
var emissions = new List<ClosedGenericMethodSetupEmission>();
foreach (var (registration, model) in Pair(registrations, models))
{
if (MockMembersBuilder.GetClosedReceiverGenericMethods(model).Count > 0)
{
emissions.Add(new ClosedGenericMethodSetupEmission(model, registration.ClosedTypeFullyQualifiedName, registration.TypeArguments));
}
}

emissions.Sort(static (x, y) => StringComparer.Ordinal.Compare(x.ClosedTypeFullyQualifiedName, y.ClosedTypeFullyQualifiedName));
return new EquatableArray<ClosedGenericMethodSetupEmission>(emissions.ToImmutableArray());
}

/// <summary>
/// Emits, per closed registration, an extension block on <c>Mock&lt;IFoo&lt;int&gt;&gt;</c> holding
/// copies of the open mock's generic-method setups. Members of a generic extension block
/// (<c>extension&lt;T&gt;(Mock&lt;IFoo&lt;T&gt;&gt; mock)</c>) do not bind when the call passes explicit
/// method type arguments, so <c>Mock.Of&lt;IFoo&lt;int&gt;&gt;().Invoke&lt;string&gt;()</c> needs a
/// closed receiver (#7302). The model's type parameters become namespace-scoped aliases for the
/// closed type arguments, so the open mock's member emitter is reused unchanged. When both blocks
/// apply, the closed receiver is the more specific and wins overload resolution.
/// </summary>
public static string BuildMethodSetups(EquatableArray<ClosedGenericMethodSetupEmission> emissions)
{
var writer = new CodeWriter();

writer.AppendLine("// <auto-generated/>");
writer.AppendLine("#pragma warning disable");
writer.AppendLine("#nullable enable");

var index = 0;
foreach (var emission in emissions)
{
var model = emission.Model;
var safeName = MockImplBuilder.GetCompositeSafeName(model);

writer.AppendLine();
using (writer.Block($"namespace {MockImplBuilder.MemberSurfaceNamespace}"))
{
for (var i = 0; i < model.TypeParameters.Length; i++)
{
writer.AppendLine($"using {model.TypeParameters[i].Name} = {emission.TypeArguments[i]};");
}

writer.AppendLine();
using (writer.Block($"internal static class {safeName}_ClosedMockMemberExtensions_{index.ToString(CultureInfo.InvariantCulture)}"))
{
using (writer.Block($"extension(global::TUnit.Mocks.Mock<{MockImplBuilder.GetMockableTypeName(model)}> mock)"))
{
var first = true;
foreach (var method in MockMembersBuilder.GetClosedReceiverGenericMethods(model))
{
if (!first) writer.AppendLine();
first = false;
MockMembersBuilder.GenerateClosedReceiverGenericMethodMembers(writer, method, model, safeName);
Comment thread
thomhurst marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread
thomhurst marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

}
}
}
}

index++;
}

return writer.ToString();
}

/// <summary>
/// Pairs each distinct registration with the open mock generated for it. Registrations whose
/// open mock was not generated as a plain single-interface mock (dropped, colliding, or bridged
/// for static abstract members) are skipped and keep using the runtime fallback.
/// </summary>
public static EquatableArray<ClosedGenericFactoryEmission> Resolve(
private static IEnumerable<(ClosedGenericMockRegistration Registration, MockTypeModel Model)> Pair(
ImmutableArray<ClosedGenericMockRegistration> registrations,
ImmutableArray<MockTypeModel> models)
{
if (registrations.IsDefaultOrEmpty)
{
return EquatableArray<ClosedGenericFactoryEmission>.Empty;
yield break;
}

var openModels = new Dictionary<string, MockTypeModel>(StringComparer.Ordinal);
Expand All @@ -71,7 +167,6 @@ public static EquatableArray<ClosedGenericFactoryEmission> Resolve(
}

var seen = new HashSet<string>(StringComparer.Ordinal);
var emissions = new List<ClosedGenericFactoryEmission>();
foreach (var registration in registrations)
{
if (!openModels.TryGetValue(registration.OpenTypeFullyQualifiedName, out var model)
Expand All @@ -81,13 +176,7 @@ public static EquatableArray<ClosedGenericFactoryEmission> Resolve(
continue;
}

emissions.Add(new ClosedGenericFactoryEmission(
registration.ClosedTypeFullyQualifiedName,
$"{MockImplBuilder.GetGlobalMockNamespacePrefix(model)}{MockImplBuilder.GetCompositeShortSafeName(model)}MockFactory.CreateAutoMock<{string.Join(", ", registration.TypeArguments)}>"));
yield return (registration, model);
}

// Ordinal order keeps the emitted file stable regardless of call-site discovery order.
emissions.Sort(static (x, y) => StringComparer.Ordinal.Compare(x.ClosedTypeFullyQualifiedName, y.ClosedTypeFullyQualifiedName));
return new EquatableArray<ClosedGenericFactoryEmission>(emissions.ToImmutableArray());
}
}
102 changes: 102 additions & 0 deletions 102 src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -898,6 +898,108 @@ private static void GenerateGenericMethodMembersInCurrentBlock(CodeWriter writer
EmitAnyArgsOverload(writer, method, model, safeName, captureModelTypeParameters: true, receiverIsThis: false);
}

/// <summary>
/// The generic methods of a generic mocked type whose setups can be re-emitted on a closed
/// receiver (<c>extension(Mock&lt;IFoo&lt;int&gt;&gt; mock)</c>) where the model's type parameters are
/// file aliases for the closed type arguments. C# does not bind a member of a generic extension
/// block when the call supplies explicit method type arguments, so without these copies
/// <c>Mock.Of&lt;IFoo&lt;int&gt;&gt;().Invoke&lt;T&gt;()</c> fails with CS1061 (#7302).
/// </summary>
/// <remarks>
/// Methods are skipped where an alias would change the meaning of the emitted code: a
/// constraint naming a model type parameter (<c>where TOther : T</c> is invalid once <c>T</c>
/// is a struct or sealed class), or an unconstrained model type parameter written as
/// <c>T?</c> (which becomes <c>Nullable&lt;T&gt;</c> for a value-type argument). Those keep the
/// typed wrapper (<c>IFoo&lt;int&gt;.Mock()</c>) and inferred calls on <c>Mock&lt;T&gt;</c>.
/// </remarks>
internal static List<MockMemberModel> GetClosedReceiverGenericMethods(MockTypeModel model)
{
var result = new List<MockMemberModel>();
if (model.TypeParameters.Length == 0)
{
return result;
}

var instanceMethods = new EquatableArray<MockMemberModel>(
model.Methods.Where(IsConfigurableMethod).ToImmutableArray());
foreach (var method in ApplyOutDisambiguation(instanceMethods))
{
if (method.TypeParameters.Length > 0 && CanAliasModelTypeParameters(method, model))
{
result.Add(method);
}
}

return result;
}

internal static void GenerateClosedReceiverGenericMethodMembers(CodeWriter writer, MockMemberModel method, MockTypeModel model, string safeName)
=> GenerateGenericMethodMembersInCurrentBlock(writer, method, model, safeName);

private static bool CanAliasModelTypeParameters(MockMemberModel method, MockTypeModel model)
{
foreach (var typeParameter in method.TypeParameters)
{
foreach (var modelTypeParameter in model.TypeParameters)
{
if (ContainsIdentifier(typeParameter.Constraints, modelTypeParameter.Name, requireNullableSuffix: false))
{
return false;
}
}
}

foreach (var modelTypeParameter in model.TypeParameters)
{
if (modelTypeParameter.HasReferenceTypeConstraint || modelTypeParameter.HasValueTypeConstraint)
{
continue;
}

if (ContainsIdentifier(method.ReturnType, modelTypeParameter.Name, requireNullableSuffix: true)
|| method.Parameters.Any(p => ContainsIdentifier(p.FullyQualifiedType, modelTypeParameter.Name, requireNullableSuffix: true)))
{
return false;
}
}

return true;
}

private static bool ContainsIdentifier(string text, string identifier, bool requireNullableSuffix)
{
if (string.IsNullOrEmpty(text))
{
return false;
}

for (var index = text.IndexOf(identifier, System.StringComparison.Ordinal); index >= 0; index = text.IndexOf(identifier, index + 1, System.StringComparison.Ordinal))
{
var end = index + identifier.Length;
if (index > 0 && IsIdentifierOrQualifierChar(text[index - 1]))
{
continue;
}

if (end < text.Length && IsIdentifierChar(text[end]))
{
continue;
}

if (!requireNullableSuffix || (end < text.Length && text[end] == '?'))
{
return true;
}
}

return false;
}

private static bool IsIdentifierChar(char c) => char.IsLetterOrDigit(c) || c == '_';

// A '.' or ':' before the name means a member or namespace-qualified type that merely shares it.
private static bool IsIdentifierOrQualifierChar(char c) => IsIdentifierChar(c) || c == '.' || c == ':';

internal static void GenerateGenericMethodMembersForWrapper(CodeWriter writer, MockMemberModel method, MockTypeModel model, string safeName)
{
if (method.HasRefStructParams)
Expand Down
24 changes: 22 additions & 2 deletions 24 src/TUnit.Mocks.SourceGenerator/MockGenerator.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -132,17 +132,37 @@ namespace TUnit.Mocks.Generated;
transform: MockTypeDiscovery.TransformGenerateMockAttributeToClosedGenericRegistrations)
.SelectMany((registrations, _) => registrations.AsImmutableArray());

var closedEmissions = closedFromMockOf
var closedInputs = closedFromMockOf
.Collect()
.Combine(closedFromAttributes.Collect())
.Combine(distinctRequests.Select(static (request, _) => request.Model).Collect())
.Combine(distinctRequests.Select(static (request, _) => request.Model).Collect());

var closedEmissions = closedInputs
.Select(static (input, _) =>
{
var ((mockOf, attributes), models) = input;
return ClosedGenericRegistrationBuilder.Resolve(mockOf.AddRange(attributes), models);
})
.WithTrackingName(MockTrackingNames.ClosedGenericEmissions);

// Step 3c: generic-method setups on Mock<IFoo<int>> need a closed receiver to accept explicit
// method type arguments, which members of the open extension<T> block cannot. See issue #7302.
var closedMethodSetups = closedInputs
.Select(static (input, _) =>
{
var ((mockOf, attributes), models) = input;
return ClosedGenericRegistrationBuilder.ResolveMethodSetups(mockOf.AddRange(attributes), models);
})
.WithTrackingName(MockTrackingNames.ClosedGenericMethodSetupEmissions);

context.RegisterSourceOutput(closedMethodSetups, static (spc, emissions) =>
{
if (emissions.Length > 0)
{
spc.AddSource(ClosedGenericRegistrationBuilder.MethodSetupsHintName, ClosedGenericRegistrationBuilder.BuildMethodSetups(emissions));
}
});

context.RegisterSourceOutput(closedEmissions, static (spc, emissions) =>
{
if (emissions.Length > 0)
Expand Down
1 change: 1 addition & 0 deletions 1 src/TUnit.Mocks.SourceGenerator/MockTrackingNames.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ internal static class MockTrackingNames
public const string EmitResults = nameof(EmitResults);
public const string ClosedGenericMockOfInvocations = nameof(ClosedGenericMockOfInvocations);
public const string ClosedGenericEmissions = nameof(ClosedGenericEmissions);
public const string ClosedGenericMethodSetupEmissions = nameof(ClosedGenericMethodSetupEmissions);
}
12 changes: 12 additions & 0 deletions 12 src/TUnit.Mocks.SourceGenerator/Models/ClosedGenericMockRegistration.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,15 @@ internal sealed record ClosedGenericMockRegistration(
internal readonly record struct ClosedGenericFactoryEmission(
string ClosedTypeFullyQualifiedName,
string FactoryMethod);

/// <summary>
/// A closed registration whose open mock has generic methods, ready to emit closed-receiver setups
/// that accept explicit method type arguments. See issue #7302.
/// </summary>
/// <param name="Model">The open mock generated for the registration.</param>
/// <param name="ClosedTypeFullyQualifiedName">The closed interface, e.g. <c>global::Ns.IRepository&lt;int&gt;</c>.</param>
/// <param name="TypeArguments">Every type argument, in model type-parameter order.</param>
internal sealed record ClosedGenericMethodSetupEmission(
MockTypeModel Model,
string ClosedTypeFullyQualifiedName,
EquatableArray<string> TypeArguments);
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402809 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.