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
+1,612 −16
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
Prev Previous commit
Next Next commit
fix(mocks): normalize closed signatures without recursive substitution (
#7302)
  • Loading branch information

Uh oh!

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

@thomhurst
thomhurst committed Nov 2, 2026
commit 8741dd581a925831f9901fdf394a8659bd54d989

There are no files selected for viewing

16 changes: 12 additions & 4 deletions 16 src/TUnit.Mocks.SourceGenerator/Builders/ClosedGenericRegistrationBuilder.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,10 @@ public static EquatableArray<ClosedGenericMethodSetupEmission> ResolveMethodSetu
var emissions = new List<ClosedGenericMethodSetupEmission>();
foreach (var (registration, model) in Pair(registrations, models))
{
if (MockMembersBuilder.GetClosedReceiverGenericMethods(model, registration.TypeArguments).Count > 0)
var methods = MockMembersBuilder.GetClosedReceiverGenericMethods(model, registration.TypeArguments);
if (methods.Count > 0)
{
emissions.Add(new ClosedGenericMethodSetupEmission(model, registration.ClosedTypeFullyQualifiedName, registration.TypeArguments));
emissions.Add(new ClosedGenericMethodSetupEmission(model, registration.ClosedTypeFullyQualifiedName, registration.TypeArguments, new EquatableArray<MockMemberModel>(methods.ToImmutableArray())));
}
}

Expand All @@ -105,14 +106,21 @@ public static string BuildMethodSetups(EquatableArray<ClosedGenericMethodSetupEm
writer.AppendLine("#pragma warning disable");
writer.AppendLine("#nullable enable");

// Keep aliases out of the member-surface namespace, where user types can share
// their names. Global imports preserve the setup surface for every consuming file.
for (var i = 0; i < emissions.Length; i++)
{
writer.AppendLine($"global using {MockImplBuilder.MemberSurfaceNamespace}.ClosedGenericMethodSetups_{i.ToString(CultureInfo.InvariantCulture)};");
}

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}"))
using (writer.Block($"namespace {MockImplBuilder.MemberSurfaceNamespace}.ClosedGenericMethodSetups_{index.ToString(CultureInfo.InvariantCulture)}"))
{
for (var i = 0; i < model.TypeParameters.Length; i++)
{
Expand All @@ -125,7 +133,7 @@ public static string BuildMethodSetups(EquatableArray<ClosedGenericMethodSetupEm
using (writer.Block($"extension(global::TUnit.Mocks.Mock<{MockImplBuilder.GetMockableTypeName(model)}> mock)"))
{
var first = true;
foreach (var method in MockMembersBuilder.GetClosedReceiverGenericMethods(model, emission.TypeArguments))
foreach (var method in emission.Methods)
{
if (!first) writer.AppendLine();
first = false;
Expand Down
9 changes: 7 additions & 2 deletions 9 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 @@ -981,10 +981,15 @@ private sealed class ClosedSignatureRewriter : CSharpSyntaxRewriter
{
private readonly Dictionary<string, TypeSyntax> _substitutions = new(System.StringComparer.Ordinal);

private ClosedSignatureRewriter() { }

public ClosedSignatureRewriter(MockTypeModel model, EquatableArray<string> arguments, MockMemberModel method)
{
// Closed arguments contain no model or method parameters. Normalize them separately
// so a canonical method name can never capture a name inside a replacement.
var normalizer = new ClosedSignatureRewriter();
for (var i = 0; i < model.TypeParameters.Length; i++)
_substitutions[model.TypeParameters[i].Name] = SyntaxFactory.ParseTypeName(arguments[i]);
_substitutions[model.TypeParameters[i].Name] = (TypeSyntax)normalizer.Visit(SyntaxFactory.ParseTypeName(arguments[i]))!;
for (var i = 0; i < method.TypeParameters.Length; i++)
_substitutions[method.TypeParameters[i].Name] = SyntaxFactory.IdentifierName("__MethodType" + i.ToString(CultureInfo.InvariantCulture));
}
Expand All @@ -994,7 +999,7 @@ public ClosedSignatureRewriter(MockTypeModel model, EquatableArray<string> argum
if (node.Parent is QualifiedNameSyntax or AliasQualifiedNameSyntax)
return base.VisitIdentifierName(node);
if (_substitutions.TryGetValue(node.Identifier.ValueText, out var replacement))
return Visit(replacement);
return replacement;
return node.Identifier.ValueText switch
{
"dynamic" => SyntaxFactory.ParseTypeName("global::System.Object"),
Expand Down
4 changes: 3 additions & 1 deletion 4 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 @@ -35,7 +35,9 @@ internal readonly record struct ClosedGenericFactoryEmission(
/// <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>
/// <param name="Methods">The collision-checked methods, computed once per registration.</param>
internal sealed record ClosedGenericMethodSetupEmission(
MockTypeModel Model,
string ClosedTypeFullyQualifiedName,
EquatableArray<string> TypeArguments);
EquatableArray<string> TypeArguments,
EquatableArray<MockMemberModel> Methods);
52 changes: 52 additions & 0 deletions 52 tests/TUnit.Mocks.SourceGenerator.Tests/Issue7302Tests.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,58 @@ public struct Point

private const string SetupsFileMarker = "_ClosedMockMemberExtensions_";

[Test]
public async Task Nullable_Containers_Are_Kept_And_Nullable_Model_Elements_Are_Skipped()
{
var setups = GetSetupsSource("""
#nullable enable
namespace TestNamespace
{
public interface INullable<T>
{
U List<U>(System.Collections.Generic.List<T>? value);
U Array<U>(T[]? value);
U Dictionary<U>(System.Collections.Generic.Dictionary<T, U?> value);
U Elements<U>(System.Collections.Generic.IEnumerable<T?> value);
}
public class Usage
{
void M() => _ = TUnit.Mocks.Mock.Of<INullable<int>>();
}
}
""");
await Assert.That(setups).IsNotNull();
await Assert.That(setups!).Contains(" List<U>(");
await Assert.That(setups).Contains(" Array<U>(");
await Assert.That(setups).Contains(" Dictionary<U>(");
await Assert.That(setups).DoesNotContain(" Elements<U>(");
}

[Test]
public async Task Canonical_Method_Type_Parameter_Names_Do_Not_Recurse_Or_Capture()
{
var setups = GetSetupsSource("""
namespace TestNamespace
{
public interface ICanonical<T>
{
U Map<U>(U value);
__MethodType0 Map<__MethodType0>(int key, __MethodType0 value);
U Collapse<U>(T value);
__MethodType0 Collapse<__MethodType0>(int value);
}
public class Usage
{
void M() => _ = TUnit.Mocks.Mock.Of<ICanonical<int>>();
}
}
""");
await Assert.That(setups).IsNotNull();
await Assert.That(setups!).Contains(" Map<U>(");
await Assert.That(setups).Contains(" Map<__MethodType0>(");
await Assert.That(setups).DoesNotContain(" Collapse<");
}

[Test]
public async Task Overloads_That_Collapse_After_Substitution_Are_Omitted()
{
Expand Down
6 changes: 4 additions & 2 deletions 6 ....Mocks.SourceGenerator.Tests/Snapshots/Closed_Generic_Method_Setups_Snapshot.verified.txt
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ file static class ClosedGenericMockFactories
// <auto-generated/>
#pragma warning disable
#nullable enable
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_0;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_1;

namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_0
{
using TContext = int;

Expand Down Expand Up @@ -81,7 +83,7 @@ namespace TUnit.Mocks.Generated
}
}

namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_1
{
using TContext = string;

Expand Down
20 changes: 13 additions & 7 deletions 20 ...ks.SourceGenerator.Tests/Snapshots/Colliding_Method_Type_Parameters_Snapshot.verified.txt
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,14 @@ file static class ClosedGenericMockFactories
// <auto-generated/>
#pragma warning disable
#nullable enable

namespace TUnit.Mocks.Generated
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_0;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_1;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_2;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_3;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_4;
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_5;

namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_0
{
using T = int;

Expand All @@ -73,7 +79,7 @@ namespace TUnit.Mocks.Generated
}
}

namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_1
{
using T = int;

Expand All @@ -97,7 +103,7 @@ namespace TUnit.Mocks.Generated
}
}

namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_2
{
using T = string;

Expand All @@ -121,7 +127,7 @@ namespace TUnit.Mocks.Generated
}
}

namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_3
{
using T = int;

Expand Down Expand Up @@ -160,7 +166,7 @@ namespace TUnit.Mocks.Generated
}
}

namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_4
{
using T = string;

Expand Down Expand Up @@ -212,7 +218,7 @@ namespace TUnit.Mocks.Generated
}
}

namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_5
{
using T = int;

Expand Down
3 changes: 2 additions & 1 deletion 3 ...ator.Tests/Snapshots/Interface_With_Type_Parameters_Named_Like_Numeric_Types.verified.txt
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -387,8 +387,9 @@ file static class ClosedGenericMockFactories
// <auto-generated/>
#pragma warning disable
#nullable enable
global using TUnit.Mocks.Generated.ClosedGenericMethodSetups_0;

namespace TUnit.Mocks.Generated
namespace TUnit.Mocks.Generated.ClosedGenericMethodSetups_0
{
using Int32 = string;

Expand Down
21 changes: 21 additions & 0 deletions 21 tests/TUnit.Mocks.Tests/Issue7302AliasTests.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using TUnit.Mocks;

namespace TUnit.Mocks.Generated
{
// An existing user type must not interfere with the namespace-scoped closed alias.
public sealed class TContext;
}

namespace TUnit.Mocks.Tests
{
public class Issue7302AliasTests
{
[Test]
public async Task User_Type_With_The_Alias_Name_Does_Not_Change_Closed_Setups()
{
var mock = Mock.Of<IMessageInvoker7302<int>>();
mock.RoundTrip<long>(1, 2L).Returns(3L);
await Assert.That(mock.Object.RoundTrip(1, 2L)).IsEqualTo(3L);
}
}
}
18 changes: 18 additions & 0 deletions 18 tests/TUnit.Mocks.Tests/Issue7302Tests.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ public interface IOverloadedInvoker7302<T>
TResult Keep<TResult>(T value);
}

public interface ICanonicalInvoker7302<T>
{
U Map<U>(U value);
__MethodType0 Map<__MethodType0>(int key, __MethodType0 value);
U Collapse<U>(T value);
__MethodType0 Collapse<__MethodType0>(int value);
}

public class Outer7302<TOuter>
{
public interface IInner<TInner>
Expand All @@ -45,6 +53,16 @@ public struct Point7302
/// </summary>
public class Issue7302Tests
{
[Test]
public async Task Canonical_Method_Type_Parameter_Names_Compile_And_Keep_Distinct_Setups()
{
var mock = Mock.Of<ICanonicalInvoker7302<int>>();
mock.Map<string>(Arg.Any<string>()).Returns("first");
mock.Map<string>(1, Arg.Any<string>()).Returns("second");
await Assert.That(mock.Object.Map("x")).IsEqualTo("first");
await Assert.That(mock.Object.Map(1, "x")).IsEqualTo("second");
}

[Test]
public async Task Closing_Overloads_Does_Not_Break_Compilation_Or_Unrelated_Setups()
{
Expand Down
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.