Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/TUnit.Mocks.SourceGenerator/Builders/MockImplBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,7 @@ private static void GenerateInterfaceMethod(CodeWriter writer, MockMemberModel m
var signatureReturnType = (method.IsVoid && !method.IsAsync) ? "void" : method.ReturnType;
var paramList = GetParameterList(method);
var typeParams = GetTypeParameterList(method);
var constraints = GetConstraintClauses(method);
var constraints = GetConstraintClauses(method, forExplicitImplementation: method.ExplicitInterfaceName is not null);

writer.AppendLineIfNotEmpty(method.ObsoleteAttribute);

Expand All @@ -599,7 +599,7 @@ private static void GenerateInterfaceMethod(CodeWriter writer, MockMemberModel m
// Return type is compatible (e.g. IEnumerable.GetEnumerator → IEnumerable<T>.GetEnumerator)
// — delegate to the public method.
var argPassList = GetArgPassList(method);
writer.AppendLine($"{signatureReturnType} {method.ExplicitInterfaceName}.{EscapeIdentifier(method.Name)}{typeParams}({paramList}){constraints} => {EscapeIdentifier(method.Name)}({argPassList});");
writer.AppendLine($"{signatureReturnType} {method.ExplicitInterfaceName}.{EscapeIdentifier(method.Name)}{typeParams}({paramList}){constraints} => {EscapeIdentifier(method.Name)}{typeParams}({argPassList});");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Account for mismatched constraints before delegating

When the hidden methods have compatible return types but different constraints, this explicit call can make otherwise valid interfaces fail to compile. For example, if the derived Get<T> requires class while the parent slot requires only notnull, the parent implementation inherits the weaker constraint and Get<T>() produces CS0452. ExplicitInterfaceCanDelegate currently checks only return-type compatibility, so constraint compatibility must also be checked before emitting this forwarding call; otherwise the parent slot needs separate dispatch.

Useful? React with 👍 / 👎.

}
else
{
Expand Down
50 changes: 50 additions & 0 deletions tests/TUnit.Mocks.SourceGenerator.Tests/Issue6670Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
namespace TUnit.Mocks.SourceGenerator.Tests;

/// <summary>
/// Regression: https://github.com/thomhurst/TUnit/issues/6670
/// A derived interface can hide a generic base method with a different return type. The base
/// slot then needs an explicit implementation, which cannot repeat inherited constraints such
/// as <c>notnull</c> (CS0460).
/// </summary>
public class Issue6670Tests : SnapshotTestBase
{
private const string Source = """
using System.Collections.Generic;
using TUnit.Mocks;

public interface ITest : ITestParent
{
new IList<T> Get<T>() where T : notnull;
}

public interface ITestParent
{
IEnumerable<T> Get<T>() where T : notnull;
}

public class TestUsage
{
void M()
{
var mock = ITest.Mock();
}
}
""";

[Test]
public async Task Hidden_Generic_Interface_Method_Does_Not_Repeat_Constraints_On_Explicit_Implementation()
{
var errors = GetGeneratedCompilationErrors(Source);
var genericImplementationErrors = errors
.Where(error => error.Id is "CS0411" or "CS0460")
.ToList();

await Assert.That(genericImplementationErrors).IsEmpty();
}

[Test]
public Task Hidden_Generic_Interface_Method_Generation_Snapshot()
{
return VerifyGeneratorOutput(Source);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
// <auto-generated/>
#pragma warning disable
#nullable enable

public sealed class ITestMock : global::TUnit.Mocks.Mock<global::ITest>, global::ITest
{
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ITestMock(global::ITest mockObject, global::TUnit.Mocks.MockEngine<global::ITest> engine)
: base(mockObject, engine) { }

global::System.Collections.Generic.IList<T> global::ITest.Get<T>() => Object.Get<T>();

global::System.Collections.Generic.IEnumerable<T> global::ITestParent.Get<T>() => ((global::ITestParent)Object).Get<T>();
}


// ===== FILE SEPARATOR =====

// <auto-generated/>
#pragma warning disable
#nullable enable

file sealed class ITestMockImpl : global::ITest, global::TUnit.Mocks.IRaisable, global::TUnit.Mocks.IMockObject
{
private readonly global::TUnit.Mocks.MockEngine<global::ITest> _engine;

[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
global::TUnit.Mocks.IMock? global::TUnit.Mocks.IMockObject.MockWrapper { get; set; }

internal ITestMockImpl(global::TUnit.Mocks.MockEngine<global::ITest> engine)
{
_engine = engine;
}

public global::System.Collections.Generic.IList<T> Get<T>() where T : notnull
{
return _engine.HandleCallWithReturn<global::System.Collections.Generic.IList<T>>(0, "Get", global::System.Array.Empty<object?>(), global::System.Array.Empty<T>(), global::TUnit.Mocks.TypeArguments.Of<T>.Value);
}

global::System.Collections.Generic.IEnumerable<T> global::ITestParent.Get<T>() => Get<T>();

[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 ITestMockFactory
{
[global::System.Runtime.CompilerServices.ModuleInitializer]
internal static void Register()
{
global::TUnit.Mocks.MockRegistry.RegisterFactory<global::ITest>(Create);
}

internal static global::TUnit.Mocks.Mock<global::ITest> CreateAutoMock(global::TUnit.Mocks.MockBehavior behavior)
{
var engine = new global::TUnit.Mocks.MockEngine<global::ITest>(behavior);
var impl = new ITestMockImpl(engine);
engine.Raisable = impl;
var mock = new ITestMock(impl, engine);
return mock;
}

internal static global::TUnit.Mocks.Mock<global::ITest> Create(global::TUnit.Mocks.MockBehavior behavior, object[] constructorArgs)
{
if (constructorArgs.Length > 0) throw new global::System.ArgumentException($"Interface mock 'global::ITest' does not support constructor arguments, but {constructorArgs.Length} were provided.");
var engine = new global::TUnit.Mocks.MockEngine<global::ITest>(behavior);
var impl = new ITestMockImpl(engine);
engine.Raisable = impl;
var mock = new ITestMock(impl, engine);
return mock;
}
}


// ===== FILE SEPARATOR =====

// <auto-generated/>
#pragma warning disable
#nullable enable

namespace TUnit.Mocks.Generated
{
public static class ITest_MockMemberExtensions
{
public static global::TUnit.Mocks.MockMethodCall<global::System.Collections.Generic.IList<T>> Get<T>(this global::TUnit.Mocks.Mock<global::ITest> mock) where T : notnull
{
var matchers = global::System.Array.Empty<global::TUnit.Mocks.Arguments.IArgumentMatcher>();
return new global::TUnit.Mocks.MockMethodCall<global::System.Collections.Generic.IList<T>>(global::TUnit.Mocks.MockRegistry.GetEngine(mock), 0, "Get", matchers, global::TUnit.Mocks.TypeArguments.Of<T>.Value);
}

#if NET9_0_OR_GREATER
[global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)]
public static void Reset(this global::TUnit.Mocks.Mock<global::ITest> mock)
=> global::TUnit.Mocks.Mock.Reset(mock);

[global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)]
public static void VerifyAll(this global::TUnit.Mocks.Mock<global::ITest> mock)
=> global::TUnit.Mocks.Mock.VerifyAll(mock);

[global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)]
public static void VerifyNoOtherCalls(this global::TUnit.Mocks.Mock<global::ITest> mock)
=> global::TUnit.Mocks.Mock.VerifyNoOtherCalls(mock);

[global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)]
public static void SetupAllProperties(this global::TUnit.Mocks.Mock<global::ITest> 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<global::ITest> mock)
=> global::TUnit.Mocks.Mock.GetDiagnostics(mock);

[global::System.Runtime.CompilerServices.OverloadResolutionPriority(-1)]
public static void SetState(this global::TUnit.Mocks.Mock<global::ITest> 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<global::ITest> mock, string stateName, global::System.Action<global::TUnit.Mocks.Mock<global::ITest>> configure)
=> global::TUnit.Mocks.Mock.InState(mock, stateName, configure);

extension(global::TUnit.Mocks.Mock<global::ITest> mock)
{
public global::System.Collections.Generic.IReadOnlyList<global::TUnit.Mocks.Verification.CallRecord> 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 =====

// <auto-generated/>
#pragma warning disable
#nullable enable

namespace TUnit.Mocks
{
public static class ITest_MockStaticExtension
{
extension(global::ITest _)
{
public static global::ITestMock Mock()
{
return (global::ITestMock)global::ITestMockFactory.CreateAutoMock(global::TUnit.Mocks.Mock.DefaultBehavior);
}

public static global::ITestMock Mock(global::TUnit.Mocks.MockBehavior behavior)
{
return (global::ITestMock)global::ITestMockFactory.CreateAutoMock(behavior);
}
}
}
}


// ===== FILE SEPARATOR =====

// <auto-generated/>
#pragma warning disable
#nullable enable

namespace TUnit.Mocks.Generated;
30 changes: 30 additions & 0 deletions tests/TUnit.Mocks.Tests/Issue6670Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using TUnit.Mocks;

namespace TUnit.Mocks.Tests;

public interface IIssue6670Test : IIssue6670TestParent
{
new IList<T> Get<T>() where T : notnull;
}

public interface IIssue6670TestParent
{
IEnumerable<T> Get<T>() where T : notnull;
}

public class Issue6670Tests
{
[Test]
public async Task Hidden_Generic_Interface_Method_Mock_Works()
{
var mock = IIssue6670Test.Mock();
var configured = new List<string> { "configured" };
mock.Get<string>().Returns(configured);

IIssue6670Test derived = mock;
IIssue6670TestParent parent = mock;

await Assert.That(derived.Get<string>()).IsSameReferenceAs(configured);
await Assert.That(parent.Get<string>()).IsSameReferenceAs(configured);
}
}
Loading