From a51648795285b685e96aea2505bb5f322a646d4e Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Fri, 18 Sep 2026 18:29:48 +0100 Subject: [PATCH 1/4] fix(mocks): emit init accessors for init-only properties and indexers The property model recorded only whether a setter existed, so an `init` accessor was emitted as a plain `set`. An implementation has to match the slot's accessor kind exactly, so mocking any type with an init-only member failed to compile with CS8854/CS8855. Carry `IPropertySymbol.SetMethod.IsInitOnly` through the member model and the explicit-interface slot model, and emit `init` from every path that writes a setter: the interface implementation (implicit and explicit), the partial and wrap overrides, the indexer variants, and the typed wrapper's forwards. An init-only member is assignable only on `this`/`base` (CS8852), so the two paths that forward by assignment can't keep doing that: the wrap override drops its pass-through to the wrapped instance, and the wrapper's explicit forward dispatches through the engine with the same member id and name the implementation uses, so setups and verifications still see one call. The partial override keeps its `base` fallback, which stays legal inside an init accessor. Fixes #6829 --- .../Builders/MockImplBuilder.cs | 38 ++-- .../Builders/MockWrapperTypeBuilder.cs | 37 +++- .../Discovery/MemberDiscovery.cs | 19 +- .../Models/MockExplicitInterfaceSlot.cs | 6 +- .../Models/MockMemberModel.cs | 9 + .../Issue6829Tests.cs | 106 +++++++++ ..._Members_Emits_Init_Accessors.verified.txt | 205 ++++++++++++++++++ tests/TUnit.Mocks.Tests/Issue6829Tests.cs | 156 +++++++++++++ 8 files changed, 550 insertions(+), 26 deletions(-) create mode 100644 tests/TUnit.Mocks.SourceGenerator.Tests/Issue6829Tests.cs create mode 100644 tests/TUnit.Mocks.SourceGenerator.Tests/Snapshots/Interface_With_Init_Only_Members_Emits_Init_Accessors.verified.txt create mode 100644 tests/TUnit.Mocks.Tests/Issue6829Tests.cs diff --git a/src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs b/src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs index 2b099ec755d..c71205fba3b 100644 --- a/src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs +++ b/src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs @@ -444,9 +444,12 @@ private static void GenerateWrapProperty(CodeWriter writer, MockMemberModel prop ? "global::System.Array.Empty()" : "new object?[] { value }"; - if (prop.IsAbstractMember) + // An init-only property cannot be assigned on the wrapped instance (CS8852 — only + // `this`/`base` are assignable from an init accessor), so it dispatches without the + // pass-through fallback the `set` path has (#6829). + if (prop.IsAbstractMember || prop.IsInitOnly) { - writer.AppendLine($"{setterPrefix}set => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", {setterArgs});"); + writer.AppendLine($"{setterPrefix}{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", {setterArgs});"); } else { @@ -951,7 +954,7 @@ private static void GenerateInterfaceProperty(CodeWriter writer, MockMemberModel if (prop.HasSetter) { writer.AppendLineIfNotEmpty(prop.SetterObsoleteAttribute); - writer.AppendLine($"set => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", new object?[] {{ value }});"); + writer.AppendLine($"{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", new object?[] {{ value }});"); } writer.CloseBrace(); return; @@ -988,11 +991,11 @@ private static void GenerateInterfaceProperty(CodeWriter writer, MockMemberModel if (prop.IsRefStructReturn) { // ref struct property — can't box value, use empty args - writer.AppendLine($"set => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", global::System.Array.Empty());"); + writer.AppendLine($"{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", global::System.Array.Empty());"); } else { - writer.AppendLine($"set => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", new object?[] {{ value }});"); + writer.AppendLine($"{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", new object?[] {{ value }});"); } } @@ -1082,12 +1085,13 @@ private static void GeneratePartialProperty(CodeWriter writer, MockMemberModel p if (prop.IsAbstractMember) { - writer.AppendLine($"{setterPrefix}set => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", {setterArgs});"); + writer.AppendLine($"{setterPrefix}{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", {setterArgs});"); } else { - // Virtual property setter: try engine, fall back to base - writer.AppendLine($"{setterPrefix}set"); + // Virtual property setter: try engine, fall back to base (assigning `base` is + // allowed from an init accessor, so init-only needs no special case here) + writer.AppendLine($"{setterPrefix}{SetterKeyword(prop)}"); writer.OpenBrace(); writer.AppendLine($"if (!_engine.TryHandleCall({prop.SetterMemberId}, \"set_{prop.Name}\", {setterArgs}))"); writer.AppendLine("{"); @@ -1120,7 +1124,7 @@ private static void GenerateInterfaceIndexer(CodeWriter writer, MockMemberModel { var setterArgs = GetIndexerSetterArgsArray(prop); writer.AppendLineIfNotEmpty(prop.SetterObsoleteAttribute); - writer.AppendLine($"set => _engine.HandleCall({prop.SetterMemberId}, \"set_Item\", {setterArgs});"); + writer.AppendLine($"{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_Item\", {setterArgs});"); } writer.CloseBrace(); @@ -1167,13 +1171,15 @@ private static void GenerateOverrideIndexer(CodeWriter writer, MockMemberModel p { var setterArgs = GetIndexerSetterArgsArray(prop); writer.AppendLineIfNotEmpty(prop.SetterObsoleteAttribute); - if (prop.IsAbstractMember) + // `base[...]` stays assignable from an init accessor, but the wrapped instance does not + // (CS8852), so an init-only wrap indexer dispatches without the fallback (#6829). + if (prop.IsAbstractMember || (prop.IsInitOnly && fallbackTarget != "base")) { - writer.AppendLine($"{setterPrefix}set => _engine.HandleCall({prop.SetterMemberId}, \"set_Item\", {setterArgs});"); + writer.AppendLine($"{setterPrefix}{SetterKeyword(prop)} => _engine.HandleCall({prop.SetterMemberId}, \"set_Item\", {setterArgs});"); } else { - writer.AppendLine($"{setterPrefix}set"); + writer.AppendLine($"{setterPrefix}{SetterKeyword(prop)}"); writer.OpenBrace(); writer.AppendLine($"if (!_engine.TryHandleCall({prop.SetterMemberId}, \"set_Item\", {setterArgs}))"); writer.OpenBrace(); @@ -1192,6 +1198,12 @@ private static string FormatIndexerParameterList(MockMemberModel indexer) private static string AccessorPrefix(string accessModifier) => accessModifier.Length == 0 ? "" : accessModifier + " "; + /// + /// The keyword the setter must be emitted with. An init slot has to be implemented by an + /// init accessor — a set accessor fails with CS8854/CS8855 (#6829). + /// + private static string SetterKeyword(MockMemberModel prop) => prop.IsInitOnly ? "init" : "set"; + private static string GetIndexerGetterArgsArray(MockMemberModel indexer) { if (indexer.Parameters.Length == 0) return "global::System.Array.Empty()"; @@ -1199,7 +1211,7 @@ private static string GetIndexerGetterArgsArray(MockMemberModel indexer) return $"new object?[] {{ {args} }}"; } - private static string GetIndexerSetterArgsArray(MockMemberModel indexer) + internal static string GetIndexerSetterArgsArray(MockMemberModel indexer) { if (indexer.Parameters.Length == 0) return "new object?[] { value }"; var args = string.Join(", ", indexer.Parameters.Select(p => p.Name)) + ", value"; diff --git a/src/TUnit.Mocks.SourceGenerator/Builders/MockWrapperTypeBuilder.cs b/src/TUnit.Mocks.SourceGenerator/Builders/MockWrapperTypeBuilder.cs index c353acc9951..48d7eab172e 100644 --- a/src/TUnit.Mocks.SourceGenerator/Builders/MockWrapperTypeBuilder.cs +++ b/src/TUnit.Mocks.SourceGenerator/Builders/MockWrapperTypeBuilder.cs @@ -134,16 +134,16 @@ private static void GeneratePropertyForwarding(CodeWriter writer, MockMemberMode var interfaceName = GetForwardingInterfaceName(prop, model); // The primary forward emits the declaring slot's OWN accessors, not the merged set, so an // asymmetric `new`-hidden slot doesn't gain an accessor it never declared (CS0550, #6263). - EmitPropertyForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName), prop.OwnHasGetter, prop.OwnHasSetter); + EmitPropertyForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName), prop.OwnHasGetter, prop.OwnHasSetter, prop.IsInitOnly); foreach (var extra in prop.AdditionalExplicitSlots) { writer.AppendLine(); - EmitPropertyForward(writer, prop, extra.InterfaceName, CastTarget(extra.InterfaceName), extra.HasGetter, extra.HasSetter); + EmitPropertyForward(writer, prop, extra.InterfaceName, CastTarget(extra.InterfaceName), extra.HasGetter, extra.HasSetter, extra.IsInitOnly); } } - private static void EmitPropertyForward(CodeWriter writer, MockMemberModel prop, string interfaceName, string target, bool hasGetter, bool hasSetter) + private static void EmitPropertyForward(CodeWriter writer, MockMemberModel prop, string interfaceName, string target, bool hasGetter, bool hasSetter, bool isInitOnly) { var returnType = prop.ReturnType; @@ -153,7 +153,14 @@ private static void EmitPropertyForward(CodeWriter writer, MockMemberModel prop, var getterAttr = GetAccessorObsoletePrefix(prop.GetterObsoleteAttribute); var setterAttr = GetAccessorObsoletePrefix(prop.SetterObsoleteAttribute); var getter = hasGetter ? $"{getterAttr}get => {target}.{EscapeIdentifier(prop.Name)}; " : ""; - var setter = hasSetter ? $"{setterAttr}set => {target}.{EscapeIdentifier(prop.Name)} = value; " : ""; + var setter = hasSetter + ? isInitOnly + // An init-only slot can't be forwarded by assignment (CS8852 — only `this`/`base` + // are assignable from an init accessor), so it dispatches straight to the engine, + // exactly as the mock implementation's own init accessor does (#6829). + ? $"{setterAttr}init => {EngineDispatch(prop)}; " + : $"{setterAttr}set => {target}.{EscapeIdentifier(prop.Name)} = value; " + : ""; writer.AppendLine($"{returnType} {interfaceName}.{EscapeIdentifier(prop.Name)} {{ {getter}{setter}}}"); } @@ -161,16 +168,16 @@ private static void EmitPropertyForward(CodeWriter writer, MockMemberModel prop, private static void GenerateIndexerForwarding(CodeWriter writer, MockMemberModel prop, MockTypeModel model) { var interfaceName = GetForwardingInterfaceName(prop, model); - EmitIndexerForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName), prop.OwnHasGetter, prop.OwnHasSetter); + EmitIndexerForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName), prop.OwnHasGetter, prop.OwnHasSetter, prop.IsInitOnly); foreach (var extra in prop.AdditionalExplicitSlots) { writer.AppendLine(); - EmitIndexerForward(writer, prop, extra.InterfaceName, CastTarget(extra.InterfaceName), extra.HasGetter, extra.HasSetter); + EmitIndexerForward(writer, prop, extra.InterfaceName, CastTarget(extra.InterfaceName), extra.HasGetter, extra.HasSetter, extra.IsInitOnly); } } - private static void EmitIndexerForward(CodeWriter writer, MockMemberModel prop, string interfaceName, string target, bool hasGetter, bool hasSetter) + private static void EmitIndexerForward(CodeWriter writer, MockMemberModel prop, string interfaceName, string target, bool hasGetter, bool hasSetter, bool isInitOnly) { var returnType = prop.ReturnType; var paramList = MockImplBuilder.GetParameterList(prop); @@ -181,11 +188,25 @@ private static void EmitIndexerForward(CodeWriter writer, MockMemberModel prop, var getterAttr = GetAccessorObsoletePrefix(prop.GetterObsoleteAttribute); var setterAttr = GetAccessorObsoletePrefix(prop.SetterObsoleteAttribute); var getter = hasGetter ? $"{getterAttr}get => {target}[{argPassList}]; " : ""; - var setter = hasSetter ? $"{setterAttr}set => {target}[{argPassList}] = value; " : ""; + var setter = hasSetter + ? isInitOnly + // See EmitPropertyForward: an init-only slot can't be forwarded by assignment (#6829). + ? $"{setterAttr}init => {EngineDispatch(prop, "set_Item", MockImplBuilder.GetIndexerSetterArgsArray(prop))}; " + : $"{setterAttr}set => {target}[{argPassList}] = value; " + : ""; writer.AppendLine($"{returnType} {interfaceName}.this[{paramList}] {{ {getter}{setter}}}"); } + /// + /// Dispatches a setter through the wrapper's own engine, for slots the wrapper cannot forward + /// by assignment. Uses the same member id and member name the mock implementation dispatches + /// with, so setups and verifications see one call either way. + /// + private static string EngineDispatch(MockMemberModel prop, string? memberName = null, string? args = null) + => $"global::TUnit.Mocks.MockRegistry.GetEngine(this).HandleCall({prop.SetterMemberId}, " + + $"\"{memberName ?? "set_" + prop.Name}\", {args ?? "new object?[] { value }"})"; + // Cast the underlying Object to a specific interface so an explicit forward dispatches to // that interface's slot (necessary when distinct slots share a signature — e.g. a `new`-hidden // base member, or wrapping a real object whose explicit impls differ per interface). diff --git a/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs b/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs index 2ff4d5fd8d5..91d2fcd898e 100644 --- a/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs +++ b/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs @@ -101,8 +101,10 @@ private static bool RequiresExplicitImpl(INamedTypeSymbol? primaryClassSymbol, I /// /: the accessors declared by the /// shadowed slot itself, so the wrapper forward for it emits only those (asymmetric new /// hiding — CS0550, #6263). Both true for methods, where accessor presence is irrelevant. + /// Whether the slot's setter is an init accessor, which the + /// forward has to match exactly (CS8855, #6829). Irrelevant for methods, hence the default. private static void RecordAdditionalWrapperInterface(List members, int index, string interfaceFqn, - bool slotHasGetter, bool slotHasSetter) + bool slotHasGetter, bool slotHasSetter, bool slotIsInitOnly = false) { var existing = members[index]; var ownSlot = existing.ExplicitInterfaceName ?? existing.DeclaringInterfaceName; @@ -113,7 +115,8 @@ private static void RecordAdditionalWrapperInterface(List membe { InterfaceName = interfaceFqn, HasGetter = slotHasGetter, - HasSetter = slotHasSetter + HasSetter = slotHasSetter, + IsInitOnly = slotIsInitOnly }; members[index] = existing with { @@ -296,7 +299,8 @@ private static void CollectMembers( // the accessors this slot declares (#6263). RecordAdditionalWrapperInterface(state.Properties, existingIndex.Value, interfaceFqn, IsAccessorAccessible(property.GetMethod, compilationAssembly), - IsAccessorAccessible(property.SetMethod, compilationAssembly)); + IsAccessorAccessible(property.SetMethod, compilationAssembly), + property.SetMethod?.IsInitOnly == true); } // else: class-primary walk and the existing member already covers // every accessor the interface needs — plain dedup. @@ -332,7 +336,8 @@ private static void CollectMembers( { RecordAdditionalWrapperInterface(state.Properties, existingIndex.Value, interfaceFqn, IsAccessorAccessible(indexer.GetMethod, compilationAssembly), - IsAccessorAccessible(indexer.SetMethod, compilationAssembly)); + IsAccessorAccessible(indexer.SetMethod, compilationAssembly), + indexer.SetMethod?.IsInitOnly == true); } } else if (primaryClassSymbol is not null && state.SeenExplicitImpls.Add($"{interfaceFqn}|{key}")) @@ -782,6 +787,10 @@ private static void MergePropertyAccessors(List properties, int { HasGetter = existing.HasGetter || newGetterAccessible, HasSetter = existing.HasSetter || newSetterAccessible, + // The merged member's accessor kind follows whichever slot contributed the setter; a + // slot that only widens an already-present setter cannot change it (#6829). + IsInitOnly = existing.HasSetter ? existing.IsInitOnly + : newSetterAccessible ? newProperty.SetMethod?.IsInitOnly == true : existing.IsInitOnly, SetterMemberId = existing.HasSetter ? existing.SetterMemberId : newSetterAccessible ? memberIdCounter++ : existing.SetterMemberId }; @@ -814,6 +823,7 @@ private static MockMemberModel CreatePropertyModel(IPropertySymbol property, ref IsProperty = true, HasGetter = hasGetter, HasSetter = hasSetter, + IsInitOnly = hasSetter && property.SetMethod?.IsInitOnly == true, OwnHasGetter = hasGetter, OwnHasSetter = hasSetter, SetterMemberId = setterId, @@ -937,6 +947,7 @@ private static MockMemberModel CreateIndexerModel(IPropertySymbol indexer, ref i IsIndexer = true, HasGetter = hasGetter, HasSetter = hasSetter, + IsInitOnly = hasSetter && indexer.SetMethod?.IsInitOnly == true, OwnHasGetter = hasGetter, OwnHasSetter = hasSetter, Parameters = new EquatableArray( diff --git a/src/TUnit.Mocks.SourceGenerator/Models/MockExplicitInterfaceSlot.cs b/src/TUnit.Mocks.SourceGenerator/Models/MockExplicitInterfaceSlot.cs index e02c12e6ed7..eaec74798b0 100644 --- a/src/TUnit.Mocks.SourceGenerator/Models/MockExplicitInterfaceSlot.cs +++ b/src/TUnit.Mocks.SourceGenerator/Models/MockExplicitInterfaceSlot.cs @@ -16,13 +16,16 @@ internal sealed record MockExplicitInterfaceSlot : IEquatableWhether this slot's setter is an init accessor (#6829). + public bool IsInitOnly { get; init; } public bool Equals(MockExplicitInterfaceSlot? other) { if (other is null) return false; return InterfaceName == other.InterfaceName && HasGetter == other.HasGetter - && HasSetter == other.HasSetter; + && HasSetter == other.HasSetter + && IsInitOnly == other.IsInitOnly; } public override int GetHashCode() @@ -33,6 +36,7 @@ public override int GetHashCode() hash = hash * 31 + InterfaceName.GetHashCode(); hash = hash * 31 + HasGetter.GetHashCode(); hash = hash * 31 + HasSetter.GetHashCode(); + hash = hash * 31 + IsInitOnly.GetHashCode(); return hash; } } diff --git a/src/TUnit.Mocks.SourceGenerator/Models/MockMemberModel.cs b/src/TUnit.Mocks.SourceGenerator/Models/MockMemberModel.cs index 7cb334648b1..10bc0bc58fe 100644 --- a/src/TUnit.Mocks.SourceGenerator/Models/MockMemberModel.cs +++ b/src/TUnit.Mocks.SourceGenerator/Models/MockMemberModel.cs @@ -18,6 +18,14 @@ internal sealed record MockMemberModel : IEquatable public bool IsProperty { get; init; } public bool HasGetter { get; init; } public bool HasSetter { get; init; } + /// + /// Whether the setter is an init accessor rather than a set accessor. The + /// implementation must match the interface/base slot exactly or the build fails with + /// CS8854/CS8855 (#6829), so every emitted accessor keys off this flag. An init-only property + /// can only be assigned on this/base, which also rules out the wrapped-instance + /// and wrapper-forward assignments the set paths emit (CS8852). + /// + public bool IsInitOnly { get; init; } public int SetterMemberId { get; init; } public bool IsIndexer { get; init; } public bool IsGenericMethod { get; init; } @@ -158,6 +166,7 @@ public bool Equals(MockMemberModel? other) && IsProperty == other.IsProperty && HasGetter == other.HasGetter && HasSetter == other.HasSetter + && IsInitOnly == other.IsInitOnly && SetterMemberId == other.SetterMemberId && IsIndexer == other.IsIndexer && IsGenericMethod == other.IsGenericMethod diff --git a/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6829Tests.cs b/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6829Tests.cs new file mode 100644 index 00000000000..22578712660 --- /dev/null +++ b/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6829Tests.cs @@ -0,0 +1,106 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace TUnit.Mocks.SourceGenerator.Tests; + +// Regression: https://github.com/thomhurst/TUnit/discussions/6829 +// The property model recorded only "has a setter", so an `init` accessor came out as a plain +// `set` — CS8854/CS8855, because an implementation must match the slot's accessor kind. The +// generated mock implementation, the typed wrapper's explicit forwards and the wrap/partial +// overrides all have to emit `init`, and because an init-only member is assignable only on +// `this`/`base` (CS8852), the forwarding paths dispatch through the engine instead. +public class Issue6829Tests : SnapshotTestBase +{ + private const string InitOnlyInterfaceSource = """ + using TUnit.Mocks; + + namespace TestNamespace; + + public interface IInitOnlyValue + { + int Value { get; init; } + string Mutable { get; set; } + string this[int index] { get; init; } + } + + public class Usage + { + void M() + { + _ = IInitOnlyValue.Mock(); + } + } + """; + + private const string InitOnlyClassSource = """ + using TUnit.Mocks; + + namespace TestNamespace; + + public abstract class AbstractInitOnly + { + public abstract int Value { get; init; } + public abstract string this[int index] { get; init; } + } + + public class VirtualInitOnly + { + public virtual int Value { get; init; } + } + + public interface IInitOnlyValue + { + int Value { get; init; } + } + + public class Usage + { + public void Test() + { + _ = Mock.Of(); + _ = Mock.Of(); + _ = Mock.Of(); + _ = Mock.Wrap(new VirtualInitOnly()); + } + } + """; + + [Test] + public Task Interface_With_Init_Only_Members_Emits_Init_Accessors() + => VerifyGeneratorOutput(InitOnlyInterfaceSource); + + [Test] + public void Init_Only_Members_Compile_For_Every_Mock_Shape() + => AssertMockImplementationsCompile(InitOnlyClassSource); + + /// + /// Compiles the generated implementations, wrapper and factories. The convenience files built + /// from C# 14 extension blocks are omitted because the harness's Roslyn predates them — the + /// runtime Issue6829Tests in TUnit.Mocks.Tests compiles the complete output with the SDK. + /// + private static void AssertMockImplementationsCompile(string source) + { + var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview); + var input = CSharpCompilation.Create("InitOnlyRegression", + [CSharpSyntaxTree.ParseText(source, options)], GetCachedReferences(), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + .WithNullableContextOptions(NullableContextOptions.Enable)); + GeneratorDriver driver = CSharpGeneratorDriver.Create( + [new MockGenerator().AsSourceGenerator()], parseOptions: options); + driver.RunGeneratorsAndUpdateCompilation(input, out var output, out var diagnostics); + + output = output.RemoveSyntaxTrees(output.SyntaxTrees.Where(tree => + tree.FilePath.EndsWith("_MockMembers.g.cs", StringComparison.Ordinal) + || tree.FilePath.EndsWith("_MockSecondaryMembers.g.cs", StringComparison.Ordinal) + || tree.FilePath.EndsWith("_MockStaticExtension.g.cs", StringComparison.Ordinal))); + + using var stream = new MemoryStream(); + var result = output.Emit(stream); + var errors = diagnostics.Concat(result.Diagnostics) + .Where(d => d.Severity == DiagnosticSeverity.Error).ToArray(); + if (errors.Length > 0) + { + throw new InvalidOperationException(string.Join(Environment.NewLine, errors.Select(d => d.ToString()))); + } + } +} diff --git a/tests/TUnit.Mocks.SourceGenerator.Tests/Snapshots/Interface_With_Init_Only_Members_Emits_Init_Accessors.verified.txt b/tests/TUnit.Mocks.SourceGenerator.Tests/Snapshots/Interface_With_Init_Only_Members_Emits_Init_Accessors.verified.txt new file mode 100644 index 00000000000..d71b3718aed --- /dev/null +++ b/tests/TUnit.Mocks.SourceGenerator.Tests/Snapshots/Interface_With_Init_Only_Members_Emits_Init_Accessors.verified.txt @@ -0,0 +1,205 @@ +// +#pragma warning disable +#nullable enable + +namespace TUnit.Mocks.Generated; + +// ===== FILE SEPARATOR ===== + +// +#pragma warning disable +#nullable enable + +namespace TestNamespace +{ + public sealed class IInitOnlyValueMock : global::TUnit.Mocks.Mock, global::TestNamespace.IInitOnlyValue + { + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + internal IInitOnlyValueMock(global::TestNamespace.IInitOnlyValue mockObject, global::TUnit.Mocks.MockEngine engine) + : base(mockObject, engine) { } + + int global::TestNamespace.IInitOnlyValue.Value { get => Object.Value; init => global::TUnit.Mocks.MockRegistry.GetEngine(this).HandleCall(1, "set_Value", new object?[] { value }); } + + string global::TestNamespace.IInitOnlyValue.Mutable { get => Object.Mutable; set => Object.Mutable = value; } + + string global::TestNamespace.IInitOnlyValue.this[int index] { get => Object[index]; init => global::TUnit.Mocks.MockRegistry.GetEngine(this).HandleCall(5, "set_Item", new object?[] { index, value }); } + } +} + + +// ===== FILE SEPARATOR ===== + +// +#pragma warning disable +#nullable enable + +namespace TestNamespace +{ + file sealed class IInitOnlyValueMockImpl : global::TestNamespace.IInitOnlyValue, global::TUnit.Mocks.IRaisable, global::TUnit.Mocks.IMockObject + { + private readonly global::TUnit.Mocks.MockEngine _engine; + + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + global::TUnit.Mocks.IMock? global::TUnit.Mocks.IMockObject.MockWrapper { get; set; } + + internal IInitOnlyValueMockImpl(global::TUnit.Mocks.MockEngine engine) + { + _engine = engine; + } + + public int Value + { + get => _engine.HandleCallWithReturn(0, "get_Value", global::System.Array.Empty(), default); + init => _engine.HandleCall(1, "set_Value", new object?[] { value }); + } + + public string Mutable + { + get => _engine.HandleCallWithReturn(2, "get_Mutable", global::System.Array.Empty(), ""); + set => _engine.HandleCall(3, "set_Mutable", new object?[] { value }); + } + + public string this[int index] + { + get => _engine.HandleCallWithReturn(4, "get_Item", new object?[] { index }, ""); + init => _engine.HandleCall(5, "set_Item", new object?[] { index, value }); + } + + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public void RaiseEvent(string eventName, object? args) + { + throw new global::System.InvalidOperationException($"No event named '{eventName}' exists on this mock."); + } + } + + internal static class IInitOnlyValueMockFactory + { + [global::System.Runtime.CompilerServices.ModuleInitializer] + internal static void Register() + { + global::TUnit.Mocks.MockRegistry.RegisterFactory(Create); + } + + internal static global::TUnit.Mocks.Mock CreateAutoMock(global::TUnit.Mocks.MockBehavior behavior) + { + var engine = new global::TUnit.Mocks.MockEngine(behavior); + var impl = new IInitOnlyValueMockImpl(engine); + engine.Raisable = impl; + var mock = new IInitOnlyValueMock(impl, engine); + return mock; + } + + internal static global::TUnit.Mocks.Mock Create(global::TUnit.Mocks.MockBehavior behavior, object[] constructorArgs) + { + if (constructorArgs.Length > 0) throw new global::System.ArgumentException($"Interface mock 'global::TestNamespace.IInitOnlyValue' does not support constructor arguments, but {constructorArgs.Length} were provided."); + var engine = new global::TUnit.Mocks.MockEngine(behavior); + var impl = new IInitOnlyValueMockImpl(engine); + engine.Raisable = impl; + var mock = new IInitOnlyValueMock(impl, engine); + return mock; + } + } +} + + +// ===== FILE SEPARATOR ===== + +// +#pragma warning disable +#nullable enable + +namespace TUnit.Mocks.Generated +{ + public static class TestNamespace_IInitOnlyValue_MockMemberExtensions + { + extension(global::TUnit.Mocks.Mock mock) + { + public global::TUnit.Mocks.PropertyMockCall Value + => new(global::TUnit.Mocks.MockRegistry.GetEngine(mock), 0, 1, "Value", true, true); + + public global::TUnit.Mocks.PropertyMockCall Mutable + => new(global::TUnit.Mocks.MockRegistry.GetEngine(mock), 2, 3, "Mutable", true, true); + } + + public static global::TUnit.Mocks.MockMethodCall Item(this global::TUnit.Mocks.Mock mock, global::TUnit.Mocks.Arguments.Arg index) + { + var matchers = new global::TUnit.Mocks.Arguments.IArgumentMatcher[] { index.Matcher }; + return new global::TUnit.Mocks.MockMethodCall(global::TUnit.Mocks.MockRegistry.GetEngine(mock), 4, "get_Item", matchers); + } + + public static global::TUnit.Mocks.VoidMockMethodCall SetItem(this global::TUnit.Mocks.Mock mock, global::TUnit.Mocks.Arguments.Arg index, global::TUnit.Mocks.Arguments.Arg value) + { + var matchers = new global::TUnit.Mocks.Arguments.IArgumentMatcher[] { index.Matcher, value.Matcher }; + return new global::TUnit.Mocks.VoidMockMethodCall(global::TUnit.Mocks.MockRegistry.GetEngine(mock), 5, "set_Item", matchers); + } + + #if NET9_0_OR_GREATER + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void Reset(this global::TUnit.Mocks.Mock mock) + => global::TUnit.Mocks.Mock.Reset(mock); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void VerifyAll(this global::TUnit.Mocks.Mock mock) + => global::TUnit.Mocks.Mock.VerifyAll(mock); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void VerifyNoOtherCalls(this global::TUnit.Mocks.Mock mock) + => global::TUnit.Mocks.Mock.VerifyNoOtherCalls(mock); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void SetupAllProperties(this global::TUnit.Mocks.Mock mock) + => global::TUnit.Mocks.Mock.SetupAllProperties(mock); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static global::TUnit.Mocks.Diagnostics.MockDiagnostics GetDiagnostics(this global::TUnit.Mocks.Mock mock) + => global::TUnit.Mocks.Mock.GetDiagnostics(mock); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void SetState(this global::TUnit.Mocks.Mock mock, string? stateName) + => global::TUnit.Mocks.Mock.SetState(mock, stateName); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void InState(this global::TUnit.Mocks.Mock mock, string stateName, global::System.Action> configure) + => global::TUnit.Mocks.Mock.InState(mock, stateName, configure); + + extension(global::TUnit.Mocks.Mock mock) + { + public global::System.Collections.Generic.IReadOnlyList Invocations => global::TUnit.Mocks.Mock.Invocations(mock); + + public global::TUnit.Mocks.MockBehavior Behavior => global::TUnit.Mocks.Mock.Behavior(mock); + + public global::TUnit.Mocks.IDefaultValueProvider? DefaultValueProvider + { + get => global::TUnit.Mocks.Mock.GetDefaultValueProvider(mock); + set => global::TUnit.Mocks.Mock.SetDefaultValueProvider(mock, value); + } + } + #endif + } +} + + +// ===== FILE SEPARATOR ===== + +// +#pragma warning disable +#nullable enable + +namespace TUnit.Mocks +{ + public static class TestNamespace_IInitOnlyValue_MockStaticExtension + { + extension(global::TestNamespace.IInitOnlyValue _) + { + public static global::TestNamespace.IInitOnlyValueMock Mock() + { + return (global::TestNamespace.IInitOnlyValueMock)global::TestNamespace.IInitOnlyValueMockFactory.CreateAutoMock(global::TUnit.Mocks.Mock.DefaultBehavior); + } + + public static global::TestNamespace.IInitOnlyValueMock Mock(global::TUnit.Mocks.MockBehavior behavior) + { + return (global::TestNamespace.IInitOnlyValueMock)global::TestNamespace.IInitOnlyValueMockFactory.CreateAutoMock(behavior); + } + } + } +} diff --git a/tests/TUnit.Mocks.Tests/Issue6829Tests.cs b/tests/TUnit.Mocks.Tests/Issue6829Tests.cs new file mode 100644 index 00000000000..dd8db119336 --- /dev/null +++ b/tests/TUnit.Mocks.Tests/Issue6829Tests.cs @@ -0,0 +1,156 @@ +using TUnit.Mocks; +using TUnit.Mocks.Arguments; + +namespace TUnit.Mocks.Tests; + +// Regression: https://github.com/thomhurst/TUnit/discussions/6829 +// The property model recorded only "has a setter", so an `init` accessor was emitted as a +// plain `set` — CS8854/CS8855, because an implementation has to match the slot's accessor +// kind exactly. Init-only members must be emitted as `init`, and because an init-only +// property is assignable only on `this`/`base` (CS8852), the wrap and wrapper-forward paths +// dispatch through the engine instead of assigning the underlying instance. + +#region Test types + +// The discussion's repro shape. +public interface IInitOnlyValue +{ + int Value { get; init; } +} + +// Mixes accessor kinds so the plain `set` path stays covered alongside `init`. +public interface IMixedAccessorKinds +{ + int InitOnly { get; init; } + string Mutable { get; set; } + string ReadOnly { get; } +} + +public interface IInitOnlyIndexer +{ + string this[int index] { get; init; } +} + +public abstract class AbstractInitOnlyProperty +{ + public abstract int Value { get; init; } + public abstract string this[int index] { get; init; } +} + +public class VirtualInitOnlyProperty +{ + public virtual int Value { get; init; } = 7; +} + +// A separate type for the wrap path: one type reached by both `.Mock()` and `Mock.Wrap` +// trips a duplicate-hint-name failure in the generator that predates this fix. +public class WrappableInitOnlyProperty +{ + public virtual int Value { get; init; } = 7; +} + +#endregion + +public class Issue6829Tests +{ + [Test] + public async Task Interface_With_Init_Only_Property_Can_Be_Mocked() + { + var mock = IInitOnlyValue.Mock(); + + await Assert.That(mock.Object.Value).IsEqualTo(0); + } + + [Test] + public async Task Init_Only_Property_Getter_Can_Be_Configured() + { + var mock = IInitOnlyValue.Mock(); + mock.Value.Returns(42); + + await Assert.That(mock.Object.Value).IsEqualTo(42); + } + + [Test] + public async Task Init_Only_Property_Is_Reachable_Through_The_Typed_Wrapper() + { + var mock = IInitOnlyValue.Mock(); + mock.Value.Returns(13); + + // The wrapper implements IInitOnlyValue explicitly, including the init accessor. + IInitOnlyValue asInterface = mock; + + await Assert.That(asInterface.Value).IsEqualTo(13); + } + + [Test] + public async Task Init_Only_Setter_Is_Verifiable_And_Unset_By_Default() + { + var mock = IInitOnlyValue.Mock(); + + mock.Value.Setter.WasNeverCalled(); + mock.Value.Set(Arg.Any()).WasNeverCalled(); + + await Assert.That(mock.Object.Value).IsEqualTo(0); + } + + [Test] + public async Task Init_Only_And_Mutable_Accessors_Coexist() + { + var mock = IMixedAccessorKinds.Mock(); + mock.InitOnly.Returns(5); + mock.Mutable.Returns("configured"); + mock.ReadOnly.Returns("readonly"); + + mock.Object.Mutable = "assigned"; + + await Assert.That(mock.Object.InitOnly).IsEqualTo(5); + await Assert.That(mock.Object.ReadOnly).IsEqualTo("readonly"); + mock.Mutable.Set("assigned").WasCalled(); + } + + [Test] + public async Task Interface_With_Init_Only_Indexer_Can_Be_Mocked() + { + var mock = IInitOnlyIndexer.Mock(); + mock.Item(1).Returns("one"); + + await Assert.That(mock.Object[1]).IsEqualTo("one"); + mock.SetItem(Arg.Any(), Arg.Any()).WasNeverCalled(); + } + + [Test] + public async Task Abstract_Class_With_Init_Only_Members_Can_Be_Mocked() + { + var mock = AbstractInitOnlyProperty.Mock(); + mock.Value.Returns(9); + mock.Item(0).Returns("zero"); + + await Assert.That(mock.Object.Value).IsEqualTo(9); + await Assert.That(mock.Object[0]).IsEqualTo("zero"); + } + + [Test] + public async Task Virtual_Init_Only_Property_Falls_Back_To_The_Base_Value() + { + var mock = VirtualInitOnlyProperty.Mock(); + + await Assert.That(mock.Object.Value).IsEqualTo(7); + + mock.Value.Returns(21); + + await Assert.That(mock.Object.Value).IsEqualTo(21); + } + + [Test] + public async Task Wrapped_Instance_Keeps_Serving_An_Init_Only_Property() + { + var real = new WrappableInitOnlyProperty { Value = 11 }; + var mock = Mock.Wrap(real); + + await Assert.That(mock.Object.Value).IsEqualTo(11); + + mock.Value.Returns(33); + + await Assert.That(mock.Object.Value).IsEqualTo(33); + } +} From 34e850f02e68e8641185c633f6c682d9b3bcf041 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Fri, 18 Sep 2026 19:20:59 +0100 Subject: [PATCH 2/4] fix(mocks): split clashing set/init interface slots into explicit impls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When two same-signature interface slots declare setters of different kinds — one `set`, one `init` — they were merged into a single implicit member. One member cannot implement both, because each implementation has to match its slot's accessor kind, so the generated mock failed with CS8854/CS8855. This shape never compiled; emitting `init` fixed the accessor kind for one slot and left the other mismatched. Detect the collision during discovery and give the clashing slot its own explicit interface implementation instead of merging it. The explicit model reuses the shared member's ids, so both slots dispatch on one logical member and a single setup or verification still covers whichever slot the caller goes through. Supporting changes: - Interface indexers honour `ExplicitInterfaceName` when emitting their declaration; previously every indexer was declared `public`, which would be a duplicate member (CS0111). - Explicit indexers are excluded from the `Item`/`SetItem` extension surface, matching how explicit properties are already excluded — they are forwarding shims on the shared ids, so their own overloads would collide (CS0111). - The typed wrapper qualifies an implicit member's forwarding target when a same-shaped explicit sibling exists, since `Object.X` is ambiguous across the two slots. --- .../Builders/MockImplBuilder.cs | 7 +- .../Builders/MockMembersBuilder.cs | 4 + .../Builders/MockWrapperTypeBuilder.cs | 23 +- .../Discovery/MemberDiscovery.cs | 50 ++++- .../Issue6829Tests.cs | 39 ++++ ...nds_Split_Into_Explicit_Slots.verified.txt | 210 ++++++++++++++++++ tests/TUnit.Mocks.Tests/Issue6829Tests.cs | 58 +++++ 7 files changed, 385 insertions(+), 6 deletions(-) create mode 100644 tests/TUnit.Mocks.SourceGenerator.Tests/Snapshots/Clashing_Setter_Kinds_Split_Into_Explicit_Slots.verified.txt diff --git a/src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs b/src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs index c71205fba3b..5f7c9c960e8 100644 --- a/src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs +++ b/src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs @@ -1110,7 +1110,12 @@ private static void GenerateInterfaceIndexer(CodeWriter writer, MockMemberModel { var paramList = FormatIndexerParameterList(prop); writer.AppendLineIfNotEmpty(prop.ObsoleteAttribute); - writer.AppendLine($"public {prop.ReturnType} this[{paramList}]"); + // An explicit slot dispatches on the same member ids as the implicit indexer, but it has to + // be declared explicitly: the two differ only in accessor kind, so declaring both publicly + // would be a duplicate member (CS0111, #6829). + writer.AppendLine(prop.ExplicitInterfaceName is not null + ? $"{prop.ReturnType} {prop.ExplicitInterfaceName}.this[{paramList}]" + : $"public {prop.ReturnType} this[{paramList}]"); writer.OpenBrace(); if (prop.HasGetter) diff --git a/src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs b/src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs index 1dd18317068..9da55ad3446 100644 --- a/src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs +++ b/src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs @@ -134,9 +134,13 @@ public static string Build(MockTypeModel model) // Indexers -- expose as Item(...)/SetItem(..., value) extension methods so // setups and verifications can target distinct index values independently. // Each indexer overload (different parameter signature) gets its own pair. + // Explicit implementations are skipped for the same reason as explicit properties: + // they are forwarding shims sharing the implicit member's ids, so generating their + // own Item/SetItem would duplicate an existing overload (CS0111, #6829). var indexers = model.Properties .Where(p => p.IsIndexer && p.IsSignatureAccessibleFromAssembly + && p.ExplicitInterfaceName is null && !p.IsStaticAbstract && !p.IsRefStructReturn && !p.IsReturnTypeStaticAbstractInterface) diff --git a/src/TUnit.Mocks.SourceGenerator/Builders/MockWrapperTypeBuilder.cs b/src/TUnit.Mocks.SourceGenerator/Builders/MockWrapperTypeBuilder.cs index 48d7eab172e..983211352dc 100644 --- a/src/TUnit.Mocks.SourceGenerator/Builders/MockWrapperTypeBuilder.cs +++ b/src/TUnit.Mocks.SourceGenerator/Builders/MockWrapperTypeBuilder.cs @@ -134,7 +134,7 @@ private static void GeneratePropertyForwarding(CodeWriter writer, MockMemberMode var interfaceName = GetForwardingInterfaceName(prop, model); // The primary forward emits the declaring slot's OWN accessors, not the merged set, so an // asymmetric `new`-hidden slot doesn't gain an accessor it never declared (CS0550, #6263). - EmitPropertyForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName), prop.OwnHasGetter, prop.OwnHasSetter, prop.IsInitOnly); + EmitPropertyForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName, model), prop.OwnHasGetter, prop.OwnHasSetter, prop.IsInitOnly); foreach (var extra in prop.AdditionalExplicitSlots) { @@ -168,7 +168,7 @@ private static void EmitPropertyForward(CodeWriter writer, MockMemberModel prop, private static void GenerateIndexerForwarding(CodeWriter writer, MockMemberModel prop, MockTypeModel model) { var interfaceName = GetForwardingInterfaceName(prop, model); - EmitIndexerForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName), prop.OwnHasGetter, prop.OwnHasSetter, prop.IsInitOnly); + EmitIndexerForward(writer, prop, interfaceName, GetPrimaryTarget(prop, interfaceName, model), prop.OwnHasGetter, prop.OwnHasSetter, prop.IsInitOnly); foreach (var extra in prop.AdditionalExplicitSlots) { @@ -219,11 +219,26 @@ private static string GetForwardingInterfaceName(MockMemberModel member, MockTyp // to the slot's interface when the member is an explicit interface impl on the underlying object, // or when it also satisfies other slots — otherwise `Object.X` may be ambiguous (CS0121) or bind // to the wrong slot (#6252). - private static string GetPrimaryTarget(MockMemberModel member, string interfaceName) - => member.ExplicitInterfaceName is not null || member.AdditionalExplicitSlots.Length > 0 + private static string GetPrimaryTarget(MockMemberModel member, string interfaceName, MockTypeModel? model = null) + => member.ExplicitInterfaceName is not null + || member.AdditionalExplicitSlots.Length > 0 + || (model is not null && HasExplicitSiblingSlot(member, model)) ? CastTarget(interfaceName) : "Object"; + /// + /// Whether another property or indexer of the same shape is implemented explicitly for a + /// different interface — the case where two slots share a signature but cannot share one member + /// (clashing set/init accessor kinds, #6829). Object.X is ambiguous across + /// those two slots, so the implicit member's forward has to name the slot it targets. + /// + private static bool HasExplicitSiblingSlot(MockMemberModel member, MockTypeModel model) + => member.ExplicitInterfaceName is null + && model.Properties.Any(other => other.ExplicitInterfaceName is not null + && other.IsIndexer == member.IsIndexer + && other.Name == member.Name + && other.ReturnType == member.ReturnType); + private static string GetAccessorObsoletePrefix(string obsoleteAttribute) => obsoleteAttribute.Length > 0 ? obsoleteAttribute + " " : ""; diff --git a/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs b/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs index 91d2fcd898e..36039ad0c36 100644 --- a/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs +++ b/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs @@ -279,6 +279,17 @@ private static void CollectMembers( // Signature collision with different return type → explicit interface impl state.Properties.Add(Tag(CreatePropertyModel(property, ref state.MemberIdCounter, interfaceFqn, interfaceFqn, compilationAssembly, compilation), ownerTypeIndex)); } + else if (HasSetterKindCollision(existingProp, property, compilationAssembly)) + { + // Same signature, different setter kinds (`set` vs `init`) — one + // member cannot implement both slots, because each implementation + // has to match its slot's accessor kind (CS8854/CS8855, #6829). + // This slot gets its own explicit impl instead of being merged. + if (state.SeenExplicitImpls.Add($"{interfaceFqn}|{key}")) + { + state.Properties.Add(Tag(CreateExplicitSlotAlias(property, existingProp, interfaceFqn, compilationAssembly, compilation), ownerTypeIndex)); + } + } else if (primaryClassSymbol is not null && ((!existingProp.HasGetter && property.GetMethod is not null) || (!existingProp.HasSetter && property.SetMethod is not null))) @@ -326,7 +337,16 @@ private static void CollectMembers( var key = $"I:[{paramTypes}]"; if (state.SeenProperties.TryGetValue(key, out var existingIndex)) { - if (existingIndex.HasValue) + if (existingIndex.HasValue + && HasSetterKindCollision(state.Properties[existingIndex.Value], indexer, compilationAssembly)) + { + // See the property case: clashing setter kinds can't share a member. + if (state.SeenExplicitImpls.Add($"{interfaceFqn}|{key}")) + { + state.Properties.Add(Tag(CreateExplicitSlotAlias(indexer, state.Properties[existingIndex.Value], interfaceFqn, compilationAssembly, compilation), ownerTypeIndex)); + } + } + else if (existingIndex.HasValue) { MergePropertyAccessors(state.Properties, existingIndex.Value, indexer, ref state.MemberIdCounter, compilationAssembly); // Distinct indexer slot hidden by `new` (or inherited twice) — the @@ -796,6 +816,34 @@ private static void MergePropertyAccessors(List properties, int }; } + /// + /// Whether declares a setter of a different kind (set vs + /// init) than the member already collected for the same signature. Such slots cannot + /// share one implicit implementation — an implementation has to match its slot's accessor kind + /// exactly — so the caller gives this slot its own explicit interface implementation (#6829). + /// + private static bool HasSetterKindCollision(MockMemberModel existing, IPropertySymbol property, + IAssemblySymbol? compilationAssembly) + => existing.HasSetter + && IsAccessorAccessible(property.SetMethod, compilationAssembly) + && existing.IsInitOnly != property.SetMethod!.IsInitOnly; + + /// + /// Builds an explicit-interface model for a slot that cannot share the implicit member's + /// accessors. It keeps the shared member's ids, so both slots dispatch on one logical member + /// and a single setup or verification still covers whichever slot the caller goes through. + /// + private static MockMemberModel CreateExplicitSlotAlias(IPropertySymbol property, MockMemberModel shared, + string interfaceFqn, IAssemblySymbol? compilationAssembly, Compilation compilation) + { + var unusedIds = 0; + var model = property.IsIndexer + ? CreateIndexerModel(property, ref unusedIds, interfaceFqn, interfaceFqn, compilationAssembly, compilation) + : CreatePropertyModel(property, ref unusedIds, interfaceFqn, interfaceFqn, compilationAssembly, compilation); + + return model with { MemberId = shared.MemberId, SetterMemberId = shared.SetterMemberId }; + } + /// /// Returns true if the accessor exists AND is accessible from the compilation assembly. /// Needed because e.g. `internal set` on an external type exists in the symbol but can't be overridden. diff --git a/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6829Tests.cs b/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6829Tests.cs index 22578712660..0c2f4b854dd 100644 --- a/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6829Tests.cs +++ b/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6829Tests.cs @@ -65,10 +65,49 @@ public void Test() } """; + // Same signature, different setter kinds: neither slot can be dropped and one member cannot + // implement both, so the `set` slot is split off into an explicit interface implementation that + // dispatches on the shared member ids. + private const string MixedSetterKindsSource = """ + using TUnit.Mocks; + + namespace TestNamespace; + + public interface IInitSlot + { + int V { get; init; } + string this[int i] { get; init; } + } + + public interface ISetSlot + { + int V { get; set; } + string this[int i] { get; set; } + } + + public interface IBothSlots : IInitSlot, ISetSlot; + + public class Usage + { + void M() + { + _ = Mock.Of(); + } + } + """; + [Test] public Task Interface_With_Init_Only_Members_Emits_Init_Accessors() => VerifyGeneratorOutput(InitOnlyInterfaceSource); + [Test] + public Task Clashing_Setter_Kinds_Split_Into_Explicit_Slots() + => VerifyGeneratorOutput(MixedSetterKindsSource); + + [Test] + public void Clashing_Setter_Kinds_Compile() + => AssertMockImplementationsCompile(MixedSetterKindsSource); + [Test] public void Init_Only_Members_Compile_For_Every_Mock_Shape() => AssertMockImplementationsCompile(InitOnlyClassSource); diff --git a/tests/TUnit.Mocks.SourceGenerator.Tests/Snapshots/Clashing_Setter_Kinds_Split_Into_Explicit_Slots.verified.txt b/tests/TUnit.Mocks.SourceGenerator.Tests/Snapshots/Clashing_Setter_Kinds_Split_Into_Explicit_Slots.verified.txt new file mode 100644 index 00000000000..56367abb850 --- /dev/null +++ b/tests/TUnit.Mocks.SourceGenerator.Tests/Snapshots/Clashing_Setter_Kinds_Split_Into_Explicit_Slots.verified.txt @@ -0,0 +1,210 @@ +// +#pragma warning disable +#nullable enable + +namespace TUnit.Mocks.Generated; + +// ===== FILE SEPARATOR ===== + +// +#pragma warning disable +#nullable enable + +namespace TestNamespace +{ + public sealed class IBothSlotsMock : global::TUnit.Mocks.Mock, global::TestNamespace.IBothSlots + { + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + internal IBothSlotsMock(global::TestNamespace.IBothSlots mockObject, global::TUnit.Mocks.MockEngine engine) + : base(mockObject, engine) { } + + int global::TestNamespace.IInitSlot.V { get => ((global::TestNamespace.IInitSlot)Object).V; init => global::TUnit.Mocks.MockRegistry.GetEngine(this).HandleCall(1, "set_V", new object?[] { value }); } + + string global::TestNamespace.IInitSlot.this[int i] { get => ((global::TestNamespace.IInitSlot)Object)[i]; init => global::TUnit.Mocks.MockRegistry.GetEngine(this).HandleCall(3, "set_Item", new object?[] { i, value }); } + + int global::TestNamespace.ISetSlot.V { get => ((global::TestNamespace.ISetSlot)Object).V; set => ((global::TestNamespace.ISetSlot)Object).V = value; } + + string global::TestNamespace.ISetSlot.this[int i] { get => ((global::TestNamespace.ISetSlot)Object)[i]; set => ((global::TestNamespace.ISetSlot)Object)[i] = value; } + } +} + + +// ===== FILE SEPARATOR ===== + +// +#pragma warning disable +#nullable enable + +namespace TestNamespace +{ + file sealed class IBothSlotsMockImpl : global::TestNamespace.IBothSlots, global::TUnit.Mocks.IRaisable, global::TUnit.Mocks.IMockObject + { + private readonly global::TUnit.Mocks.MockEngine _engine; + + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + global::TUnit.Mocks.IMock? global::TUnit.Mocks.IMockObject.MockWrapper { get; set; } + + internal IBothSlotsMockImpl(global::TUnit.Mocks.MockEngine engine) + { + _engine = engine; + } + + public int V + { + get => _engine.HandleCallWithReturn(0, "get_V", global::System.Array.Empty(), default); + init => _engine.HandleCall(1, "set_V", new object?[] { value }); + } + + public string this[int i] + { + get => _engine.HandleCallWithReturn(2, "get_Item", new object?[] { i }, ""); + init => _engine.HandleCall(3, "set_Item", new object?[] { i, value }); + } + + int global::TestNamespace.ISetSlot.V + { + get => _engine.HandleCallWithReturn(0, "get_V", global::System.Array.Empty(), default); + set => _engine.HandleCall(1, "set_V", new object?[] { value }); + } + + string global::TestNamespace.ISetSlot.this[int i] + { + get => _engine.HandleCallWithReturn(2, "get_Item", new object?[] { i }, ""); + set => _engine.HandleCall(3, "set_Item", new object?[] { i, value }); + } + + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public void RaiseEvent(string eventName, object? args) + { + throw new global::System.InvalidOperationException($"No event named '{eventName}' exists on this mock."); + } + } + + internal static class IBothSlotsMockFactory + { + [global::System.Runtime.CompilerServices.ModuleInitializer] + internal static void Register() + { + global::TUnit.Mocks.MockRegistry.RegisterFactory(Create); + } + + internal static global::TUnit.Mocks.Mock CreateAutoMock(global::TUnit.Mocks.MockBehavior behavior) + { + var engine = new global::TUnit.Mocks.MockEngine(behavior); + var impl = new IBothSlotsMockImpl(engine); + engine.Raisable = impl; + var mock = new IBothSlotsMock(impl, engine); + return mock; + } + + internal static global::TUnit.Mocks.Mock Create(global::TUnit.Mocks.MockBehavior behavior, object[] constructorArgs) + { + if (constructorArgs.Length > 0) throw new global::System.ArgumentException($"Interface mock 'global::TestNamespace.IBothSlots' does not support constructor arguments, but {constructorArgs.Length} were provided."); + var engine = new global::TUnit.Mocks.MockEngine(behavior); + var impl = new IBothSlotsMockImpl(engine); + engine.Raisable = impl; + var mock = new IBothSlotsMock(impl, engine); + return mock; + } + } +} + + +// ===== FILE SEPARATOR ===== + +// +#pragma warning disable +#nullable enable + +namespace TUnit.Mocks.Generated +{ + public static class TestNamespace_IBothSlots_MockMemberExtensions + { + extension(global::TUnit.Mocks.Mock mock) + { + public global::TUnit.Mocks.PropertyMockCall V + => new(global::TUnit.Mocks.MockRegistry.GetEngine(mock), 0, 1, "V", true, true); + } + + public static global::TUnit.Mocks.MockMethodCall Item(this global::TUnit.Mocks.Mock mock, global::TUnit.Mocks.Arguments.Arg i) + { + var matchers = new global::TUnit.Mocks.Arguments.IArgumentMatcher[] { i.Matcher }; + return new global::TUnit.Mocks.MockMethodCall(global::TUnit.Mocks.MockRegistry.GetEngine(mock), 2, "get_Item", matchers); + } + + public static global::TUnit.Mocks.VoidMockMethodCall SetItem(this global::TUnit.Mocks.Mock mock, global::TUnit.Mocks.Arguments.Arg i, global::TUnit.Mocks.Arguments.Arg value) + { + var matchers = new global::TUnit.Mocks.Arguments.IArgumentMatcher[] { i.Matcher, value.Matcher }; + return new global::TUnit.Mocks.VoidMockMethodCall(global::TUnit.Mocks.MockRegistry.GetEngine(mock), 3, "set_Item", matchers); + } + + #if NET9_0_OR_GREATER + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void Reset(this global::TUnit.Mocks.Mock mock) + => global::TUnit.Mocks.Mock.Reset(mock); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void VerifyAll(this global::TUnit.Mocks.Mock mock) + => global::TUnit.Mocks.Mock.VerifyAll(mock); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void VerifyNoOtherCalls(this global::TUnit.Mocks.Mock mock) + => global::TUnit.Mocks.Mock.VerifyNoOtherCalls(mock); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void SetupAllProperties(this global::TUnit.Mocks.Mock mock) + => global::TUnit.Mocks.Mock.SetupAllProperties(mock); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static global::TUnit.Mocks.Diagnostics.MockDiagnostics GetDiagnostics(this global::TUnit.Mocks.Mock mock) + => global::TUnit.Mocks.Mock.GetDiagnostics(mock); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void SetState(this global::TUnit.Mocks.Mock mock, string? stateName) + => global::TUnit.Mocks.Mock.SetState(mock, stateName); + + [global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)] + public static void InState(this global::TUnit.Mocks.Mock mock, string stateName, global::System.Action> configure) + => global::TUnit.Mocks.Mock.InState(mock, stateName, configure); + + extension(global::TUnit.Mocks.Mock mock) + { + public global::System.Collections.Generic.IReadOnlyList Invocations => global::TUnit.Mocks.Mock.Invocations(mock); + + public global::TUnit.Mocks.MockBehavior Behavior => global::TUnit.Mocks.Mock.Behavior(mock); + + public global::TUnit.Mocks.IDefaultValueProvider? DefaultValueProvider + { + get => global::TUnit.Mocks.Mock.GetDefaultValueProvider(mock); + set => global::TUnit.Mocks.Mock.SetDefaultValueProvider(mock, value); + } + } + #endif + } +} + + +// ===== FILE SEPARATOR ===== + +// +#pragma warning disable +#nullable enable + +namespace TUnit.Mocks +{ + public static class TestNamespace_IBothSlots_MockStaticExtension + { + extension(global::TestNamespace.IBothSlots _) + { + public static global::TestNamespace.IBothSlotsMock Mock() + { + return (global::TestNamespace.IBothSlotsMock)global::TestNamespace.IBothSlotsMockFactory.CreateAutoMock(global::TUnit.Mocks.Mock.DefaultBehavior); + } + + public static global::TestNamespace.IBothSlotsMock Mock(global::TUnit.Mocks.MockBehavior behavior) + { + return (global::TestNamespace.IBothSlotsMock)global::TestNamespace.IBothSlotsMockFactory.CreateAutoMock(behavior); + } + } + } +} diff --git a/tests/TUnit.Mocks.Tests/Issue6829Tests.cs b/tests/TUnit.Mocks.Tests/Issue6829Tests.cs index dd8db119336..b20c65518bc 100644 --- a/tests/TUnit.Mocks.Tests/Issue6829Tests.cs +++ b/tests/TUnit.Mocks.Tests/Issue6829Tests.cs @@ -49,6 +49,23 @@ public class WrappableInitOnlyProperty public virtual int Value { get; init; } = 7; } +// Same signature, different setter kinds. Neither slot can be dropped and one member cannot +// implement both, so the `set` slot becomes an explicit interface implementation that dispatches +// on the same member ids as the implicit `init` one. +public interface IInitSlot +{ + int V { get; init; } + string this[int i] { get; init; } +} + +public interface ISetSlot +{ + int V { get; set; } + string this[int i] { get; set; } +} + +public interface IBothSetterKinds : IInitSlot, ISetSlot; + #endregion public class Issue6829Tests @@ -141,6 +158,47 @@ public async Task Virtual_Init_Only_Property_Falls_Back_To_The_Base_Value() await Assert.That(mock.Object.Value).IsEqualTo(21); } + [Test] + public async Task Clashing_Setter_Kinds_Serve_Both_Slots_From_One_Setup() + { + var mock = IBothSetterKinds.Mock(); + mock.V.Returns(5); + mock.Item(2).Returns("two"); + + // One setup covers both slots — the explicit `set` slot shares the implicit slot's ids. + await Assert.That(((IInitSlot)mock.Object).V).IsEqualTo(5); + await Assert.That(((ISetSlot)mock.Object).V).IsEqualTo(5); + await Assert.That(((IInitSlot)mock.Object)[2]).IsEqualTo("two"); + await Assert.That(((ISetSlot)mock.Object)[2]).IsEqualTo("two"); + } + + [Test] + public async Task Clashing_Setter_Kinds_Verify_Through_The_Shared_Member() + { + var mock = IBothSetterKinds.Mock(); + + ((ISetSlot)mock.Object).V = 9; + ((ISetSlot)mock.Object)[1] = "one"; + + mock.V.Set(9).WasCalled(); + mock.SetItem(1, "one").WasCalled(); + + await Assert.That(mock.Invocations).HasCount(2); + } + + [Test] + public async Task Clashing_Setter_Kinds_Are_Reachable_Through_The_Typed_Wrapper() + { + var mock = IBothSetterKinds.Mock(); + mock.V.Returns(4); + + IBothSetterKinds asInterface = mock; + ((ISetSlot)asInterface).V = 7; + + await Assert.That(((IInitSlot)asInterface).V).IsEqualTo(4); + mock.V.Set(7).WasCalled(); + } + [Test] public async Task Wrapped_Instance_Keeps_Serving_An_Init_Only_Property() { From e048f5cd77a041921f194db9f8f45433d70f9d9a Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Fri, 18 Sep 2026 19:36:14 +0100 Subject: [PATCH 3/4] refactor(mocks): scope the indexer surface exclusion to shared-slot aliases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The exclusion added with the slot split keyed off `ExplicitInterfaceName`, which is broader than the intent: an explicit indexer that owns its member ids (a class-primary mock re-implementing an interface indexer the class already implements non-virtually) would lose its `Item`/`SetItem` surface if such a model ever reached the members builder. Mark the alias itself instead — `IsSharedSlotAlias` is set only by `CreateExplicitSlotAlias`, the one place a member reuses another's ids — and filter on that. Explicit indexers owning their ids keep their surface, and the reason for the exclusion is now stated by the flag rather than inferred from the accessor kind. Generated output is unchanged: the composite models that carry those explicit indexers emit their setup surface from the secondary pair model, which is built from the standalone interface and never marks members explicit. --- .../Builders/MockMembersBuilder.cs | 10 +++---- .../Discovery/MemberDiscovery.cs | 7 ++++- .../Models/MockMemberModel.cs | 9 ++++++ tests/TUnit.Mocks.Tests/Issue6829Tests.cs | 29 +++++++++++++++++++ 4 files changed, 49 insertions(+), 6 deletions(-) diff --git a/src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs b/src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs index 9da55ad3446..91d8574ab55 100644 --- a/src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs +++ b/src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs @@ -133,14 +133,14 @@ public static string Build(MockTypeModel model) // Indexers -- expose as Item(...)/SetItem(..., value) extension methods so // setups and verifications can target distinct index values independently. - // Each indexer overload (different parameter signature) gets its own pair. - // Explicit implementations are skipped for the same reason as explicit properties: - // they are forwarding shims sharing the implicit member's ids, so generating their - // own Item/SetItem would duplicate an existing overload (CS0111, #6829). + // Each indexer overload (different parameter signature) gets its own pair, except + // an alias sharing another indexer's ids — that indexer already generates the pair, + // and a second copy would be a duplicate overload (CS0111, #6829). An explicit + // indexer that owns its ids keeps its own surface. var indexers = model.Properties .Where(p => p.IsIndexer && p.IsSignatureAccessibleFromAssembly - && p.ExplicitInterfaceName is null + && !p.IsSharedSlotAlias && !p.IsStaticAbstract && !p.IsRefStructReturn && !p.IsReturnTypeStaticAbstractInterface) diff --git a/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs b/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs index 36039ad0c36..346521702ff 100644 --- a/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs +++ b/src/TUnit.Mocks.SourceGenerator/Discovery/MemberDiscovery.cs @@ -841,7 +841,12 @@ private static MockMemberModel CreateExplicitSlotAlias(IPropertySymbol property, ? CreateIndexerModel(property, ref unusedIds, interfaceFqn, interfaceFqn, compilationAssembly, compilation) : CreatePropertyModel(property, ref unusedIds, interfaceFqn, interfaceFqn, compilationAssembly, compilation); - return model with { MemberId = shared.MemberId, SetterMemberId = shared.SetterMemberId }; + return model with + { + MemberId = shared.MemberId, + SetterMemberId = shared.SetterMemberId, + IsSharedSlotAlias = true + }; } /// diff --git a/src/TUnit.Mocks.SourceGenerator/Models/MockMemberModel.cs b/src/TUnit.Mocks.SourceGenerator/Models/MockMemberModel.cs index 10bc0bc58fe..1a75881acaf 100644 --- a/src/TUnit.Mocks.SourceGenerator/Models/MockMemberModel.cs +++ b/src/TUnit.Mocks.SourceGenerator/Models/MockMemberModel.cs @@ -26,6 +26,14 @@ internal sealed record MockMemberModel : IEquatable /// and wrapper-forward assignments the set paths emit (CS8852). /// public bool IsInitOnly { get; init; } + /// + /// Whether this member is an explicit interface implementation that reuses another member's + /// ids rather than owning its own. Emitted when two slots share a signature but cannot share + /// one implementation (clashing set/init accessor kinds, #6829): both dispatch on + /// one logical member, so the alias must not also claim the setup and verification surface — + /// that member already generates it, and a second copy would be a duplicate overload (CS0111). + /// + public bool IsSharedSlotAlias { get; init; } public int SetterMemberId { get; init; } public bool IsIndexer { get; init; } public bool IsGenericMethod { get; init; } @@ -167,6 +175,7 @@ public bool Equals(MockMemberModel? other) && HasGetter == other.HasGetter && HasSetter == other.HasSetter && IsInitOnly == other.IsInitOnly + && IsSharedSlotAlias == other.IsSharedSlotAlias && SetterMemberId == other.SetterMemberId && IsIndexer == other.IsIndexer && IsGenericMethod == other.IsGenericMethod diff --git a/tests/TUnit.Mocks.Tests/Issue6829Tests.cs b/tests/TUnit.Mocks.Tests/Issue6829Tests.cs index b20c65518bc..1bd745b8a21 100644 --- a/tests/TUnit.Mocks.Tests/Issue6829Tests.cs +++ b/tests/TUnit.Mocks.Tests/Issue6829Tests.cs @@ -66,6 +66,23 @@ public interface ISetSlot public interface IBothSetterKinds : IInitSlot, ISetSlot; +// An explicit indexer that owns its member ids, rather than aliasing another one: the class +// implements the interface indexer non-virtually, so the mock can only intercept it by +// re-implementing the interface explicitly. Its setup surface must survive. +public interface IIndexedService +{ + string this[int index] { get; set; } +} + +public class BlockingIndexerService : IIndexedService +{ + public string this[int index] + { + get => $"real-{index}"; + set { } + } +} + #endregion public class Issue6829Tests @@ -199,6 +216,18 @@ public async Task Clashing_Setter_Kinds_Are_Reachable_Through_The_Typed_Wrapper( mock.V.Set(7).WasCalled(); } + [Test] + public async Task Explicit_Indexer_Owning_Its_Ids_Keeps_Its_Setup_Surface() + { + var mock = Mock.Of(); + mock.Item(1).Returns("mocked"); + + await Assert.That(((IIndexedService)mock.Object)[1]).IsEqualTo("mocked"); + + ((IIndexedService)mock.Object)[2] = "written"; + mock.SetItem(2, "written").WasCalled(); + } + [Test] public async Task Wrapped_Instance_Keeps_Serving_An_Init_Only_Property() { From 676e36c0b538b1b5f4ad8b1f7feed2f87e25858d Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Fri, 18 Sep 2026 20:11:50 +0100 Subject: [PATCH 4/4] test(mocks): use the TFM-safe Mock.Invocations helper The instance-style `mock.Invocations` is an extension member polyfilled only on net9.0 and later, so the test failed to build on net8.0 with CS1061. Every other test uses the static `Mock.Invocations(mock)` helper, which is available on all target frameworks. --- tests/TUnit.Mocks.Tests/Issue6829Tests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/TUnit.Mocks.Tests/Issue6829Tests.cs b/tests/TUnit.Mocks.Tests/Issue6829Tests.cs index 1bd745b8a21..b730b0fca7e 100644 --- a/tests/TUnit.Mocks.Tests/Issue6829Tests.cs +++ b/tests/TUnit.Mocks.Tests/Issue6829Tests.cs @@ -200,7 +200,7 @@ public async Task Clashing_Setter_Kinds_Verify_Through_The_Shared_Member() mock.V.Set(9).WasCalled(); mock.SetItem(1, "one").WasCalled(); - await Assert.That(mock.Invocations).HasCount(2); + await Assert.That(Mock.Invocations(mock).Count).IsEqualTo(2); } [Test]