diff --git a/src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs b/src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs index 2b099ec755d..5f7c9c960e8 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("{"); @@ -1106,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) @@ -1120,7 +1129,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 +1176,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 +1203,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 +1216,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/MockMembersBuilder.cs b/src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs index 1dd18317068..91d8574ab55 100644 --- a/src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs +++ b/src/TUnit.Mocks.SourceGenerator/Builders/MockMembersBuilder.cs @@ -133,10 +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. + // 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.IsSharedSlotAlias && !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 c353acc9951..983211352dc 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, model), 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, model), 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). @@ -198,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 2ff4d5fd8d5..346521702ff 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 { @@ -276,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))) @@ -296,7 +310,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. @@ -322,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 @@ -332,7 +356,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,11 +807,48 @@ 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 }; } + /// + /// 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, + IsSharedSlotAlias = true + }; + } + /// /// 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. @@ -814,6 +876,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 +1000,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..1a75881acaf 100644 --- a/src/TUnit.Mocks.SourceGenerator/Models/MockMemberModel.cs +++ b/src/TUnit.Mocks.SourceGenerator/Models/MockMemberModel.cs @@ -18,6 +18,22 @@ 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; } + /// + /// 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; } @@ -158,6 +174,8 @@ public bool Equals(MockMemberModel? other) && IsProperty == other.IsProperty && 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.SourceGenerator.Tests/Issue6829Tests.cs b/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6829Tests.cs new file mode 100644 index 00000000000..0c2f4b854dd --- /dev/null +++ b/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6829Tests.cs @@ -0,0 +1,145 @@ +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()); + } + } + """; + + // 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); + + /// + /// 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/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.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..b730b0fca7e --- /dev/null +++ b/tests/TUnit.Mocks.Tests/Issue6829Tests.cs @@ -0,0 +1,243 @@ +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; +} + +// 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; + +// 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 +{ + [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 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(mock).Count).IsEqualTo(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 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() + { + 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); + } +}