diff --git a/Docs/pages/06-parameter-matching.md b/Docs/pages/06-parameter-matching.md index 35863bfde..abb942b1a 100644 --- a/Docs/pages/06-parameter-matching.md +++ b/Docs/pages/06-parameter-matching.md @@ -175,7 +175,9 @@ A matcher for a nullable type with a non-nullable type argument, such as `Setup. #### Any type argument -A setup or verification on `Setup` or `Verify` applies to one type argument. To match every type argument, use `SetupGeneric` and `VerifyGeneric`. They offer each generic method without its type parameters: a parameter whose type depends on a type parameter takes a matcher of any type, which is checked against the value of the call, or `null` for a `null` argument, independent of the other parameters, e.g. `SetupGeneric.Pair(It.IsAny(), null)`. The other parameters take a matcher of their type. Both take matchers only, so match a value with `It.Is(...)`. Generic constraints do not apply. +A setup or verification on `Setup` or `Verify` applies to one type argument. To match every type argument, use `SetupGeneric` and `VerifyGeneric`. They offer each generic method without its type parameters: a parameter whose type depends on a type parameter takes a matcher of any type, or `null` for a `null` argument, independent of the other parameters, e.g. `SetupGeneric.Pair(It.IsAny(), null)`. The other parameters take a matcher of their type. Both take matchers only, so match a value with `It.Is(...)`. Generic constraints do not apply. + +The type of the matcher selects the type arguments of the calls it matches, and the matcher then checks the value. A matcher of `object`, such as `It.IsAny()` or `It.Satisfies(...)`, matches every type argument: ```csharp public interface IChocolateSerializer @@ -189,14 +191,28 @@ serializer.Mock.SetupGeneric.Deserialize(It.Is("{")).Throws(); void Act() => serializer.Deserialize("{"); serializer.Write("dark"); +serializer.Write("milk"); serializer.Write(42); await That(Act).Throws(); await That(serializer.Mock.VerifyGeneric.Write(It.IsAny())).Once(); await That(serializer.Mock.VerifyGeneric.Write(It.IsAny())).Once(); -await That(serializer.Mock.VerifyGeneric.Write(Match.AnyParameters())).Twice(); +await That(serializer.Mock.VerifyGeneric.Write(It.Satisfies(value => value is string))).Twice(); +await That(serializer.Mock.VerifyGeneric.Write(Match.AnyParameters())).Exactly(3); ``` +In detail, a matcher of the type `M` matches a call when the type that the parameter has in the call converts to `M`: + +- For a parameter `T value`, `It.IsAny()` matches `Write(...)`, but neither `Write("milk")` nor `Write(42)`, and so does a negative matcher such as `It.IsNot("dark")`. A matcher of a base type or an interface matches the type arguments that derive from it or implement it: `It.IsAny()` matches `Write(...)` as well. +- Nullable value types convert as in C#: `It.IsAny()` matches `Write(...)`, but `It.IsAny()` does not match `Write(...)`. `It.IsAny()` matches both, as an `int?` is boxed to an `int`. +- `null` matches a `null` argument of every type argument, `It.IsNull()` only one of the type argument `string`. +- When the type of the parameter only partly depends on a type parameter, such as `IRequest`, `IEnumerable` or `T?` of a value type `T`, the matcher may also have a type that implements or derives from the type of the parameter, or the underlying type of a nullable value type; the type arguments then follow from that type, as in type inference. For `Send(IRequest request)`, `It.IsAny()` with `Ping : IRequest` matches the calls of `Send` with a `Ping`; for `Store(IEnumerable items)`, `It.IsAny>()` matches the calls of `Store` with a `List`, and, as `IEnumerable` is covariant, also those of `Store`; for `Store(T? item) where T : struct`, `It.IsAny()` matches the calls of `Store` that pass a value. +- A matcher that implements `IParameter` for several types, such as `It.Contains(...)` or `It.SequenceEquals(...)`, and a matcher given as a non-generic `IParameter` that is not one of the matchers of `It`, only checks the value, like a matcher of `object`. +- When overloads share a setup, the rule of the called overload applies: in `Overloaded(object value)` next to `Overloaded(T value)`, only the value of the parameter is checked, as it does not depend on a type argument. This also holds for a call `Overloaded(...)` of `Overloaded(T value)` from generic code, which is recorded like a call of `Overloaded(object value)`; with several such parameters, as in `P(T a, object b)` next to `P(object a, T b)`, both are then only checked by value. +- `Match.AnyParameters()` and other `IParameters` match every type argument. + +As the type argument decides, a call with a base type or an interface as type argument, e.g. `Publish(orderPlaced)`, is not matched by `It.IsAny()`. Check the value instead: `SetupGeneric.Publish(It.Satisfies(value => value is OrderPlaced))`. + Each recorded call keeps its type arguments: the `GetTypeArguments()` extension of `IMethodInteraction` (in `Mockolate.Interactions`) returns them, e.g. `[typeof(int)]` for `serializer.Write(42)`, and an empty list for a method that is not generic. It leaves out the type arguments of a generic interface or class that declares the method. To inspect the calls that a verification matched, pass a predicate to `IVerificationResult.Verify` (in `Mockolate.Verify`). Like any verification, it marks the matched calls as verified, which counts for a later check that all interactions are verified. ```csharp diff --git a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.Logging.cs b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.Logging.cs index 5a70c03a5..8b67f2e0f 100644 --- a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.Logging.cs +++ b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.Logging.cs @@ -973,7 +973,7 @@ bool IsMatchingSetup(global::Mockolate.Setup.MethodSetup candidate) { ScopeSetup scopeCandidate => scopeCandidate.MatchesScope(invocation), global::Mockolate.Setup.ReturnMethodSetup typedSetup => typedSetup.Name == name && typedSetup.Matches(state), - global::Mockolate.Setup.VoidMethodSetup anyTypeCandidate => anyTypeCandidate.Name == anyTypeName && anyTypeCandidate.Matches(state), + global::Mockolate.Setup.VoidMethodSetup anyTypeCandidate => anyTypeCandidate.Name == anyTypeName && global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(anyTypeCandidate, 0, typeof(TState), global::Mockolate.Internals.ParameterTypeDependency.TypeParameter) && anyTypeCandidate.Matches(state), _ => false, }; diff --git a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MethodSetups.cs b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MethodSetups.cs index 0f773e3bd..3a61327c3 100644 --- a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MethodSetups.cs +++ b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MethodSetups.cs @@ -917,10 +917,10 @@ private static void AppendGenericMethodSetups(StringBuilder sb, int numberOfPara $"{isCallOf}, global::Mockolate.Parameters.IParameters parameters{parameterNames}", $", parameters{parameterNameArgs}"); AppendAnyTypeArgumentsSetup("GenericMethodSetup", "WithParameterCollection", "matching against individual ", - isCallOf + parameterMatches, parameterMatchArgs); + isCallOf + parameterMatches, parameterMatchArgs, matchesParameterTypes: true); void AppendAnyTypeArgumentsSetup(string className, string baseClassName, string matching, string constructorParameters, - string constructorArguments) + string constructorArguments, bool matchesParameterTypes = false) { sb.Append("\t/// Setup for a generic method with ").Append(numberOfParameters) .Append(" parameters, for any type argument, ").Append(matching).Append(".").AppendLine(); @@ -928,7 +928,13 @@ void AppendAnyTypeArgumentsSetup(string className, string baseClassName, string AppendDebuggerNonUserCode(sb, "\t"); sb.Append("\tinternal sealed class ").Append(className).Append('<').Append(typeParams).Append("> : global::Mockolate.Setup.VoidMethodSetup<") .Append(typeParams).Append(">.").Append(baseClassName) - .Append(", global::Mockolate.Internals.IMethodSetupForAnyTypeArguments,").AppendLine(); + .Append(", global::Mockolate.Internals.IMethodSetupForAnyTypeArguments,"); + if (matchesParameterTypes) + { + sb.Append(" global::Mockolate.Internals.IGenericMethodParameterTypes,"); + } + + sb.AppendLine(); sb.Append("\t\tglobal::Mockolate.Setup.IGenericMethodSetupCallbackBuilder<").Append(typeParams) .Append(">, global::Mockolate.Setup.IGenericMethodSetupReturnBuilder<").Append(typeParams).Append('>').AppendLine(); sb.Append("\t{").AppendLine(); @@ -954,10 +960,37 @@ void AppendAnyTypeArgumentsSetup(string className, string baseClassName, string .Append(", out T").Append(i).Append(" p").Append(i).Append("Value)"); } + if (matchesParameterTypes) + { + for (int i = 1; i <= numberOfParameters; i++) + { + sb.Append(" &&").AppendLine(); + sb.Append("\t\t\t global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter").Append(i) + .Append(", invocation, ").Append(i - 1).Append(')'); + } + } + sb.Append(" &&").AppendLine(); sb.Append("\t\t\t Matches(").Append(string.Join(", ", Enumerable.Range(1, numberOfParameters).Select(i => FormattableString.Invariant($"p{i}Value")))) .Append(");").AppendLine(); sb.AppendLine(); + if (matchesParameterTypes) + { + sb.Append("\t\t/// ").AppendLine(); + sb.Append("\t\tbool global::Mockolate.Internals.IGenericMethodParameterTypes.MatchesParameterType(int index, global::System.Type parameterType, global::Mockolate.Internals.ParameterTypeDependency dependency)").AppendLine(); + sb.Append("\t\t\t=> index switch").AppendLine(); + sb.Append("\t\t\t{").AppendLine(); + for (int i = 1; i <= numberOfParameters; i++) + { + sb.Append("\t\t\t\t").Append(i - 1).Append(" => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter") + .Append(i).Append(", parameterType, dependency),").AppendLine(); + } + + sb.Append("\t\t\t\t_ => true,").AppendLine(); + sb.Append("\t\t\t};").AppendLine(); + sb.AppendLine(); + } + AppendGenericMethodSetupImplementation(sb, numberOfParameters); sb.Append("\t}").AppendLine(); sb.AppendLine(); diff --git a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.GenericSetup.cs b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.GenericSetup.cs index 8a83ab003..02dcdb963 100644 --- a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.GenericSetup.cs +++ b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.GenericSetup.cs @@ -30,7 +30,7 @@ internal static partial class SourceTemplates .Where(group => group.Select(method => GetGenericSetupName(method) + GetGenericParameterNames(method)) .Distinct().Take(2).Count() == 1) .Select(group => group.ToArray()) - .Select(overloads => (overloads[0], GetGenericFacadeParameterTypes(overloads[0]), overloads, + .Select(overloads => (overloads[0], GetGenericFacadeParameterTypes(overloads), overloads, GetGenericIsCallOf(overloads, genericMethods))) .ToList(); } @@ -59,37 +59,106 @@ private static string GetGenericIsCallOf(Method[] overloads, Method[] genericMet List alternatives = []; foreach (Method overload in overloads) { - GenericParameter[] genericParameters = overload.GenericParameters!.Value.AsArray(); - List checks = []; - int index = 0; - foreach (MethodParameter parameter in overload.Parameters) + if (GetGenericOverloadRecognition(overload, invocation) is not { } recognition) { - if (!overload.UsesTypeParameter(parameter.Type)) - { - checks.Add(FormattableString.Invariant($"{invocation}.GetParameterTypeAt({index}) == typeof({parameter.Type.IdentityName})")); - } - else if (Array.FindIndex(genericParameters, genericParameter - => string.Equals(parameter.Type.Fullname, genericParameter.Name, StringComparison.Ordinal) || - string.Equals(parameter.Type.Fullname, genericParameter.Name + "?", StringComparison.Ordinal)) - is >= 0 and int typeArgumentIndex) + return "null"; + } + + alternatives.Add(recognition); + } + + return $"static {invocation} => {string.Join(" || ", alternatives.Select(alternative => $"({alternative})"))}"; + } + + /// + /// The condition that a recorded call in the variable is a call of the + /// , by the types of its parameters, or when no parameter + /// tells, see . + /// + private static string? GetGenericOverloadRecognition(Method overload, string invocation) + { + List checks = GetGenericOverloadChecks(overload, + (index, type) => FormattableString.Invariant($"{invocation}.GetParameterTypeAt({index}) == typeof({type.IdentityName})"), + (index, typeArgumentIndex, isNullable) => FormattableString.Invariant( + $"global::Mockolate.Internals.GenericMethodInvocations.IsTypeArgument({invocation}, {index}, {typeArgumentIndex}{(isNullable ? ", true" : "")})")); + return checks.Count == 0 ? null : string.Join(" && ", checks); + } + + /// + /// The condition that a call of the would be recognized as a call of the + /// once recorded, see , in the body of the + /// : "true", "false" or an expression of its type parameters, or + /// when no parameter of the tells. + /// + private static string? GetGenericOverloadRecognitionInBody(Method overload, Method method) + { + MethodParameter[] parameters = method.Parameters.AsArray(); + GenericParameter[] typeParameters = method.GenericParameters!.Value.AsArray(); + bool isFalse = false; + List checks = GetGenericOverloadChecks(overload, + (index, type) => + { + Entities.Type parameterType = parameters[index].Type; + if (!method.UsesTypeParameter(parameterType)) { - bool isNullable = parameter.Type.Fullname.EndsWith("?", StringComparison.Ordinal) && genericParameters[typeArgumentIndex].IsValueType; - checks.Add( - FormattableString.Invariant($"global::Mockolate.Internals.GenericMethodInvocations.IsTypeArgument({invocation}, {index}, {typeArgumentIndex}{(isNullable ? ", true" : "")})")); + isFalse |= !string.Equals(parameterType.IdentityName, type.IdentityName, StringComparison.Ordinal); + return ""; } - index++; - } + return $"typeof({parameterType.IdentityName}) == typeof({type.IdentityName})"; + }, + (index, typeArgumentIndex, isNullable) => + { + string parameterType = $"typeof({parameters[index].Type.IdentityName})"; + string typeArgument = $"typeof({typeParameters[typeArgumentIndex].Name})"; + return isNullable + ? $"global::System.Nullable.GetUnderlyingType({parameterType}) == {typeArgument}" + : $"{parameterType} == {typeArgument}"; + }); + if (checks.Count == 0) + { + return null; + } + + if (isFalse) + { + return "false"; + } + + checks.RemoveAll(check => check.Length == 0); + return checks.Count == 0 ? "true" : string.Join(" && ", checks); + } - if (checks.Count == 0) + /// + /// The checks that recognize a call of the by the types of its parameters: the type + /// itself when it does not depend on a type argument (), the type argument when it is a + /// type parameter (, also for T? of a value type T). + /// + private static List GetGenericOverloadChecks(Method overload, Func isType, + Func isTypeArgument) + { + GenericParameter[] genericParameters = overload.GenericParameters!.Value.AsArray(); + List checks = []; + int index = 0; + foreach (MethodParameter parameter in overload.Parameters) + { + if (!overload.UsesTypeParameter(parameter.Type)) { - return "null"; + checks.Add(isType(index, parameter.Type)); + } + else if (Array.FindIndex(genericParameters, genericParameter + => string.Equals(parameter.Type.Fullname, genericParameter.Name, StringComparison.Ordinal) || + string.Equals(parameter.Type.Fullname, genericParameter.Name + "?", StringComparison.Ordinal)) + is >= 0 and int typeArgumentIndex) + { + bool isNullable = parameter.Type.Fullname.EndsWith("?", StringComparison.Ordinal) && genericParameters[typeArgumentIndex].IsValueType; + checks.Add(isTypeArgument(index, typeArgumentIndex, isNullable)); } - alternatives.Add(string.Join(" && ", checks)); + index++; } - return $"static {invocation} => {string.Join(" || ", alternatives.Select(alternative => $"({alternative})"))}"; + return checks; } /// @@ -206,10 +275,159 @@ internal static bool HasGenericFacadeShape(Method method) !method.HasUnsupportedRefStructReturn; private static string[] GetGenericFacadeParameterTypes(Method method) - => method.Parameters - .Select(parameter => method.UsesTypeParameter(parameter.Type) ? "object?" : parameter.Type.Fullname) + => GetGenericFacadeParameterTypes([method,]); + + /// + /// The types of the parameters on the facade for the that share it: + /// for a parameter that depends on a type argument in any of them, its own type + /// otherwise. + /// + private static string[] GetGenericFacadeParameterTypes(Method[] overloads) + => overloads[0].Parameters + .Select((parameter, index) => IsTypeDependent(overloads, index) ? "object?" : parameter.Type.Fullname) .ToArray(); + /// + /// Whether the parameter at the zero-based depends on a type argument in any of the + /// that share a facade method, so that the facade takes a matcher of any type for it. + /// + private static bool IsTypeDependent(Method[] overloads, int index) + => overloads.Any(overload => overload.UsesTypeParameter(overload.Parameters.AsArray()[index].Type)); + + /// + /// How the type of the depends on a type argument of the , + /// as a member of ParameterTypeDependency. T? is the type parameter itself unless T is a value + /// type, where it is a of it, which only partly depends on it. + /// + private static string GetParameterTypeDependency(Method method, MethodParameter parameter) + { + if (!method.UsesTypeParameter(parameter.Type)) + { + return "global::Mockolate.Internals.ParameterTypeDependency.Independent"; + } + + bool isTypeParameter = method.GenericParameters is { } genericParameters && genericParameters.Any(genericParameter + => string.Equals(parameter.Type.Fullname, genericParameter.Name, StringComparison.Ordinal) || + (string.Equals(parameter.Type.Fullname, genericParameter.Name + "?", StringComparison.Ordinal) && + !genericParameter.IsValueType)); + return isTypeParameter + ? "global::Mockolate.Internals.ParameterTypeDependency.TypeParameter" + : "global::Mockolate.Internals.ParameterTypeDependency.PartlyDependent"; + } + + /// + /// The arguments that tell a TypeArgumentParameterMatch how the type of the parameter at the zero-based + /// depends on a type argument in a recorded call: a constant when it does so the same + /// way in all , otherwise also a function that recognizes the overload of a call. + /// + /// + /// The overloads are recognized by the types of their parameters, as in , and an + /// overload that no parameter type recognizes comes last. A recorded call that two overloads could have made, + /// e.g. Foo<object>(…) of Foo<T>(T value) and Foo<T>(object value), is + /// taken as one of the overload whose parameter does not depend on a type argument, which C# chooses for it as + /// the more specific one. + /// + private static string GetGenericDependencyArguments(Method[] overloads, int index) + { + string[] dependencies = overloads + .Select(overload => GetParameterTypeDependency(overload, overload.Parameters.AsArray()[index])) + .ToArray(); + if (dependencies.Distinct(StringComparer.Ordinal).Take(2).Count() == 1) + { + return dependencies[0]; + } + + string invocation = Helpers.GetUniqueLocalVariableName("invocation", overloads[0].Parameters); + List<(Method Overload, string? Recognition, string Dependency)> alternatives = + GetGenericDependencyAlternatives(overloads, index, overload => GetGenericOverloadRecognition(overload, invocation)); + StringBuilder dependencyOf = new(); + dependencyOf.Append("static ").Append(invocation).Append(" => "); + foreach ((_, string? recognition, string dependency) in alternatives.Take(alternatives.Count - 1)) + { + if (recognition is null) + { + break; + } + + dependencyOf.Append(recognition).Append(" ? ").Append(dependency).Append(" : "); + } + + string fallback = GetGenericDependencyFallback(alternatives); + dependencyOf.Append(fallback); + return $"{fallback}, {dependencyOf}"; + } + + /// + /// The overloads with the condition that recognizes their calls and how their parameter at the zero-based + /// depends on a type argument, in the order in which they are tried: overloads + /// recognized by the type of a parameter that does not depend on a type argument first, as C# chooses them over + /// the others for a call that both could make, then the other recognized ones, then the ones that no parameter + /// type recognizes. Within each, an overload recognized by more parameters comes first, so that the condition of + /// an overload that only checks some of them, e.g. key of Add<T>(string key, IEnumerable<T> value), + /// does not take the calls of Add<T>(string key, T value). + /// + private static List<(Method Overload, string? Recognition, string Dependency)> GetGenericDependencyAlternatives( + Method[] overloads, int index, Func recognize) + => overloads + .Select(overload => (Overload: overload, Recognition: recognize(overload), + Dependency: GetParameterTypeDependency(overload, overload.Parameters.AsArray()[index]))) + .OrderBy(alternative => + { + if (alternative.Recognition is null) + { + return 2; + } + + return alternative.Dependency.EndsWith(".Independent", StringComparison.Ordinal) ? 0 : 1; + }) + .ThenByDescending(alternative => GetGenericOverloadChecks(alternative.Overload, + static (_, _) => "", static (_, _, _) => "").Count) + .ToList(); + + private static string GetGenericDependencyFallback( + List<(Method Overload, string? Recognition, string Dependency)> alternatives) + => alternatives.Find(alternative => alternative.Recognition is null).Dependency ?? + alternatives[alternatives.Count - 1].Dependency; + + /// + /// How the parameter at the zero-based of the depends on a type + /// argument in its own call, as the setups for any type argument see it once the call is recorded, see + /// : an overload of the same setup that is tried first and whose + /// calls look the same, e.g. Foo<T>(object value) for a call Foo<object>(…) of + /// Foo<T>(T value), decides. + /// + private static string GetGenericDependencyInBody(Method[] overloads, Method method, int index) + { + string own = GetParameterTypeDependency(method, method.Parameters.AsArray()[index]); + if (overloads.Length < 2) + { + return own; + } + + List<(Method Overload, string? Recognition, string Dependency)> alternatives = + GetGenericDependencyAlternatives(overloads, index, overload => GetGenericOverloadRecognitionInBody(overload, method)); + StringBuilder dependency = new(); + foreach ((Method overload, string? recognition, string alternativeDependency) in alternatives) + { + bool isRecognized = string.Equals(recognition, "true", StringComparison.Ordinal); + if (overload.Equals(method) || recognition is null || isRecognized) + { + dependency.Append(overload.Equals(method) || isRecognized + ? alternativeDependency + : GetGenericDependencyFallback(alternatives)); + return dependency.ToString(); + } + + if (!string.Equals(recognition, "false", StringComparison.Ordinal)) + { + dependency.Append(recognition).Append(" ? ").Append(alternativeDependency).Append(" : "); + } + } + + return dependency.Append(own).ToString(); + } + + private static string GetGenericFacadeName(Method method) => method.Name.Substring(0, method.Name.IndexOf('<')); @@ -242,17 +460,32 @@ private static string GetGenericSetupInterface(string[] parameterTypes) ? "global::Mockolate.Setup.IGenericMethodSetup" : $"global::Mockolate.Setup.IGenericMethodSetup<{string.Join(", ", parameterTypes)}>"; - private static (string Type, string MatchArgs)? GetGenericDispatch(Method method) + /// + /// The type of the setups for any type argument that a call of the is matched against, + /// the arguments to match, and, for each parameter whose type depends on a type argument, its index and its type + /// in the call, which the matchers of a setup check as well. + /// + private static (string Type, string MatchArgs, (int Index, string Type)[] ParameterTypes)? GetGenericDispatch( + Class @class, Method method) { if (!HasGenericFacadeShape(method)) { return null; } + Method[] overloads = GetGenericFacadeMethods(@class, method.MemberType) + .Select(facadeMethod => facadeMethod.Overloads) + .FirstOrDefault(group => group.Contains(method)) ?? [method,]; + string[] parameterTypes = GetGenericFacadeParameterTypes(method); return (GetGenericSetupType(parameterTypes), string.Join(", ", method.Parameters.Select((parameter, i) - => string.Equals(parameterTypes[i], "object?", StringComparison.Ordinal) ? $"(object?){parameter.Name}" : parameter.Name))); + => string.Equals(parameterTypes[i], "object?", StringComparison.Ordinal) ? $"(object?){parameter.Name}" : parameter.Name)), + method.Parameters + .Select((parameter, i) => (Index: i, Parameter: parameter)) + .Where(item => method.UsesTypeParameter(item.Parameter.Type)) + .Select(item => (item.Index, $"typeof({item.Parameter.Type.IdentityName}), {GetGenericDependencyInBody(overloads, method, item.Index)}")) + .ToArray()); } /// @@ -262,18 +495,18 @@ private static (string Type, string MatchArgs)? GetGenericDispatch(Method method /// parameter takes a matcher of the given type, which is a type parameter of the overload for a parameter that /// depends on a type argument. /// - private static void AppendGenericFacadeParameters(StringBuilder sb, Method method, string[] parameterTypes, + private static void AppendGenericFacadeParameters(StringBuilder sb, Method[] overloads, string[] parameterTypes, string[]? matcherTypes = null) { int index = 0; - foreach (MethodParameter parameter in method.Parameters) + foreach (MethodParameter parameter in overloads[0].Parameters) { if (index > 0) { sb.Append(", "); } - if (matcherTypes is null && method.UsesTypeParameter(parameter.Type)) + if (matcherTypes is null && IsTypeDependent(overloads, index)) { sb.Append("global::Mockolate.Parameters.IParameter? ").Append(parameter.Name); } @@ -299,12 +532,12 @@ private static void AppendGenericFacadeParameters(StringBuilder sb, Method metho /// literal cannot infer a type parameter, so it still binds to the overload that takes the non-generic /// IParameter. /// - private static (string[] MatcherTypes, string TypeParameters)? GetGenericMatcherOverload(Method method, + private static (string[] MatcherTypes, string TypeParameters)? GetGenericMatcherOverload(Method[] overloads, string[] parameterTypes) { - MethodParameter[] parameters = method.Parameters.AsArray(); + MethodParameter[] parameters = overloads[0].Parameters.AsArray(); List indices = Enumerable.Range(0, parameters.Length) - .Where(index => method.UsesTypeParameter(parameters[index].Type)) + .Where(index => IsTypeDependent(overloads, index)) .ToList(); if (indices.Count == 0) { @@ -337,15 +570,18 @@ private static (string[] MatcherTypes, string TypeParameters)? GetGenericMatcher } /// - /// A matcher matches default(T), or the declared default value of an optional - /// parameter, as a left-out argument does. A parameter that depends on a type argument can only have a - /// or default value; overloads whose declared default values - /// differ share no value, so keeps matching default(T) there. + /// A parameter whose type depends on a type argument is matched by a TypeArgumentParameterMatch, so that + /// the type of the matcher selects the type arguments of the calls it matches: the static type of the matcher in + /// the overload that takes a matcher of the exact type (), and the type of the + /// IParameter<T> that it implements in the overload that takes a non-generic IParameter. + /// For any other parameter, a matcher matches default(T), or the declared default + /// value of an optional parameter, as a left-out argument does; overloads whose declared default values differ + /// share no value, so keeps matching default(T) there. /// - private static string GetGenericParameterMatch(Method method, Method[] overloads, int index, - MethodParameter parameter, string parameterType, bool isMatcherOverload) + private static string GetGenericParameterMatch(Method[] overloads, int index, MethodParameter parameter, + string parameterType, string? matcherType) { - if (!method.UsesTypeParameter(parameter.Type)) + if (!IsTypeDependent(overloads, index)) { string nullMatch = parameter.HasExplicitDefaultValue && overloads.All(overload => overload.Parameters.AsArray()[index] is { HasExplicitDefaultValue: true, } other && @@ -355,8 +591,8 @@ private static string GetGenericParameterMatch(Method method, Method[] overloads return $"global::Mockolate.CovariantParameterAdapter<{parameterType}>.Wrap({parameter.Name} ?? {nullMatch})"; } - string cast = isMatcherOverload ? "(global::Mockolate.Parameters.IParameter?)" : ""; - return $"new global::Mockolate.CovariantParameterAdapter({cast}{parameter.Name} ?? global::Mockolate.Internals.Matchers.IsNull())"; + string typeArgument = matcherType is null ? "" : $"<{matcherType}>"; + return $"global::Mockolate.Internals.TypeArgumentParameterMatch.Create{typeArgument}({parameter.Name}, {GetGenericDependencyArguments(overloads, index)})"; } private static string GetGenericParameterNames(Method method) @@ -391,7 +627,7 @@ private static void DefineGenericSetupInterface(StringBuilder sb, sb.AppendXmlSummary(summary, "\t"); sb.Append("\tinternal interface ").Append(facadeName).AppendLine(); sb.Append("\t{").AppendLine(); - foreach ((Method method, string[] parameterTypes, _, _) in methods) + foreach ((Method method, string[] parameterTypes, Method[] overloads, _) in methods) { string setupInterface = GetGenericSetupInterface(parameterTypes); if (HasGenericParametersOverload(methods, method)) @@ -408,16 +644,16 @@ private static void DefineGenericSetupInterface(StringBuilder sb, sb.AppendXmlSummary(methodSummary); AppendGenericMatcherPriority(sb, methods, method, hasOverloadResolutionPriority); sb.Append("\t\t").Append(setupInterface).Append(' ').Append(GetGenericFacadeName(method)).Append('('); - AppendGenericFacadeParameters(sb, method, parameterTypes); + AppendGenericFacadeParameters(sb, overloads, parameterTypes); sb.Append(");").AppendLine(); sb.AppendLine(); - if (GetGenericMatcherOverload(method, parameterTypes) is (string[] matcherTypes, string typeParameters)) + if (GetGenericMatcherOverload(overloads, parameterTypes) is (string[] matcherTypes, string typeParameters)) { sb.AppendXmlSummary(methodSummary); AppendGenericMatcherPriority(sb, methods, method, hasOverloadResolutionPriority); sb.Append("\t\t").Append(setupInterface).Append(' ').Append(GetGenericFacadeName(method)).Append('<') .Append(typeParameters).Append(">("); - AppendGenericFacadeParameters(sb, method, parameterTypes, matcherTypes); + AppendGenericFacadeParameters(sb, overloads, parameterTypes, matcherTypes); sb.Append(");").AppendLine(); sb.AppendLine(); } @@ -452,7 +688,7 @@ private static void ImplementGenericSetupInterface(StringBuilder sb, } AppendSetup(matcherTypes: null, typeParameters: null); - if (GetGenericMatcherOverload(method, parameterTypes) is (string[] matcherTypes, string typeParameters)) + if (GetGenericMatcherOverload(overloads, parameterTypes) is (string[] matcherTypes, string typeParameters)) { AppendSetup(matcherTypes, typeParameters); } @@ -468,7 +704,7 @@ void AppendSetup(string[]? matcherTypes, string? typeParameters) } sb.Append('('); - AppendGenericFacadeParameters(sb, method, parameterTypes, matcherTypes); + AppendGenericFacadeParameters(sb, overloads, parameterTypes, matcherTypes); sb.Append(')').AppendLine(); sb.Append("\t\t{").AppendLine(); sb.Append("\t\t\tvar ").Append(methodSetup).Append(" = new ").Append(GetGenericSetupClass("GenericMethodSetup", parameterTypes)) @@ -482,8 +718,8 @@ void AppendSetup(string[]? matcherTypes, string? typeParameters) int index = 0; foreach (MethodParameter parameter in method.Parameters) { - sb.Append(", ").Append(GetGenericParameterMatch(method, overloads, index, parameter, - parameterTypes[index], matcherTypes is not null)); + sb.Append(", ").Append(GetGenericParameterMatch(overloads, index, parameter, parameterTypes[index], + matcherTypes?[index])); index++; } @@ -542,7 +778,7 @@ private static void DefineGenericVerifyInterface(StringBuilder sb, sb.AppendXmlSummary(summary, "\t"); sb.Append("\tinternal interface ").Append(facadeName).AppendLine(); sb.Append("\t{").AppendLine(); - foreach ((Method method, string[] parameterTypes, _, _) in methods) + foreach ((Method method, string[] parameterTypes, Method[] overloads, _) in methods) { if (HasGenericParametersOverload(methods, method)) { @@ -560,16 +796,16 @@ private static void DefineGenericVerifyInterface(StringBuilder sb, AppendGenericMatcherPriority(sb, methods, method, hasOverloadResolutionPriority); sb.Append("\t\tglobal::Mockolate.Verify.VerificationResult<").Append(resultName).Append("> ") .Append(GetGenericFacadeName(method)).Append('('); - AppendGenericFacadeParameters(sb, method, parameterTypes); + AppendGenericFacadeParameters(sb, overloads, parameterTypes); sb.Append(");").AppendLine(); sb.AppendLine(); - if (GetGenericMatcherOverload(method, parameterTypes) is (string[] matcherTypes, string typeParameters)) + if (GetGenericMatcherOverload(overloads, parameterTypes) is (string[] matcherTypes, string typeParameters)) { sb.AppendXmlSummary(methodSummary); AppendGenericMatcherPriority(sb, methods, method, hasOverloadResolutionPriority); sb.Append("\t\tglobal::Mockolate.Verify.VerificationResult<").Append(resultName).Append("> ") .Append(GetGenericFacadeName(method)).Append('<').Append(typeParameters).Append(">("); - AppendGenericFacadeParameters(sb, method, parameterTypes, matcherTypes); + AppendGenericFacadeParameters(sb, overloads, parameterTypes, matcherTypes); sb.Append(");").AppendLine(); sb.AppendLine(); } @@ -601,7 +837,7 @@ private static void ImplementGenericVerifyInterface(StringBuilder sb, } AppendVerify(matcherTypes: null, typeParameters: null); - if (GetGenericMatcherOverload(method, parameterTypes) is (string[] matcherTypes, string typeParameters)) + if (GetGenericMatcherOverload(overloads, parameterTypes) is (string[] matcherTypes, string typeParameters)) { AppendVerify(matcherTypes, typeParameters); } @@ -617,7 +853,7 @@ void AppendVerify(string[]? matcherTypes, string? typeParameters) } sb.Append('('); - AppendGenericFacadeParameters(sb, method, parameterTypes, matcherTypes); + AppendGenericFacadeParameters(sb, overloads, parameterTypes, matcherTypes); sb.Append(')').AppendLine(); sb.Append("\t\t{").AppendLine(); StringBuilder predicate = new(); @@ -627,8 +863,8 @@ void AppendVerify(string[]? matcherTypes, string? typeParameters) string match = Helpers.GetUniqueLocalVariableName(FormattableString.Invariant($"match{index + 1}"), method.Parameters); sb.Append("\t\t\tglobal::Mockolate.Parameters.IParameterMatch<").Append(parameterTypes[index]) .Append("> ").Append(match).Append(" = ") - .Append(GetGenericParameterMatch(method, overloads, index, parameter, parameterTypes[index], - matcherTypes is not null)) + .Append(GetGenericParameterMatch(overloads, index, parameter, parameterTypes[index], + matcherTypes?[index])) .Append(';').AppendLine(); if (index > 0) { @@ -669,7 +905,7 @@ void AppendVerify(string[]? matcherTypes, string? typeParameters) private static void EmitMethodSetupLookupWithGeneric(StringBuilder sb, string indent, string mockRegistry, string methodSetup, string methodSetupType, string memberIdRef, string uniqueNameString, string matchArgs, string genericSetup, string genericSetupType, string genericSetupName, string genericMatchArgs, - EquatableArray parameters) + (int Index, string Type)[] genericParameterTypes, EquatableArray parameters) #pragma warning restore S107 { string snapshotVar = Helpers.GetUniqueLocalVariableName($"snapshot_{methodSetup}", parameters); @@ -744,9 +980,16 @@ void AppendMatch(string matchIndent, string candidate) sb.Append(matchIndent).Append("\tbreak;").AppendLine(); sb.Append(matchIndent).Append('}').AppendLine(); sb.Append(matchIndent).Append("if (").Append(genericSetup).Append(" is null && ").Append(candidate).Append(" is ") - .Append(genericSetupType).Append(' ').Append(genericVar).Append(" && ").Append(genericVar).Append(".Name == ") - .Append(genericSetupName).Append(" && ").Append(genericVar).Append(".Matches(").Append(genericMatchArgs) - .Append("))").AppendLine(); + .Append(genericSetupType).Append(' ') + .Append(genericVar).Append(" && ").Append(genericVar).Append(".Name == ").Append(genericSetupName) + .Append(" && "); + foreach ((int index, string type) in genericParameterTypes) + { + sb.Append("global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(").Append(genericVar) + .Append(", ").Append(index).Append(", ").Append(type).Append(") && "); + } + + sb.Append(genericVar).Append(".Matches(").Append(genericMatchArgs).Append("))").AppendLine(); sb.Append(matchIndent).Append('{').AppendLine(); sb.Append(matchIndent).Append('\t').Append(genericSetup).Append(" = ").Append(genericVar).Append(';').AppendLine(); sb.Append(matchIndent).Append('}').AppendLine(); diff --git a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.cs b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.cs index 47ce6f1d8..b5ab939ea 100644 --- a/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.cs +++ b/Source/Mockolate.SourceGenerators/Sources/SourceTemplates.MockClass.cs @@ -3201,7 +3201,7 @@ method.ExplicitImplementation is null && string memberIdRef = memberIdPrefix + memberIds.GetMethodIdentifier(method); bool isGeneric = method.GenericParameters is not null && method.GenericParameters.Value.Count > 0; - (string Type, string MatchArgs)? genericDispatch = isGeneric ? GetGenericDispatch(method) : null; + (string Type, string MatchArgs, (int Index, string Type)[] ParameterTypes)? genericDispatch = isGeneric ? GetGenericDispatch(@class, method) : null; string? genericSetup = genericDispatch is null ? null : Helpers.GetUniqueLocalVariableName("genericMethodSetup", method.Parameters); @@ -3209,7 +3209,7 @@ method.ExplicitImplementation is null && { EmitMethodSetupLookupWithGeneric(sb, "\t\t\t", mockRegistry, methodSetup, methodSetupType, memberIdRef, method.GetUniqueNameString(), sb2.ToString(), genericSetup!, dispatch.Type, GetGenericSetupName(method), - dispatch.MatchArgs, method.Parameters); + dispatch.MatchArgs, dispatch.ParameterTypes, method.Parameters); } else { diff --git a/Source/Mockolate/Internals/GenericMethodInvocations.cs b/Source/Mockolate/Internals/GenericMethodInvocations.cs index 3cc751fab..203150d07 100644 --- a/Source/Mockolate/Internals/GenericMethodInvocations.cs +++ b/Source/Mockolate/Internals/GenericMethodInvocations.cs @@ -3,6 +3,7 @@ using System.ComponentModel; using Mockolate.Interactions; using Mockolate.Parameters; +using Mockolate.Setup; namespace Mockolate.Internals; @@ -105,8 +106,11 @@ public static bool TryGetValue(IMethodInvocationParameters invocation, int in /// /// Checks whether the argument at the zero-based matches . /// + /// + /// A also checks the type that the parameter has in the call. + /// public static bool Matches(IParameterMatch match, IMethodInvocationParameters invocation, int index) - => TryGetValue(invocation, index, out T value) && match.Matches(value); + => MatchesType(match, invocation, index) && TryGetValue(invocation, index, out T value) && match.Matches(value); /// /// Checks whether the arguments match , e.g. . @@ -140,4 +144,31 @@ public static bool Matches(IParameters parameters, IMethodInvocationParameters i return true; } } + + /// + /// Checks whether matches the type that the parameter at the zero-based + /// has in the call, which only a restricts. + /// + public static bool MatchesType(IParameterMatch match, IMethodInvocationParameters invocation, int index) + => match is not TypeArgumentParameterMatch typeArgumentMatch || + typeArgumentMatch.MatchesType(invocation, index); + + /// + /// Checks whether matches a call in which the parameter has the type + /// , which depends on a type argument as tells and + /// which only a restricts. + /// + public static bool MatchesType(IParameterMatch match, Type parameterType, ParameterTypeDependency dependency) + => match is not TypeArgumentParameterMatch typeArgumentMatch || + typeArgumentMatch.MatchesType(parameterType, dependency); + + /// + /// Checks whether the matcher of for the parameter at the zero-based + /// matches a call in which the parameter has the type , + /// which depends on a type argument as tells. + /// + public static bool MatchesParameterType(MethodSetup setup, int index, Type parameterType, + ParameterTypeDependency dependency) + => setup is not IGenericMethodParameterTypes parameterTypes || + parameterTypes.MatchesParameterType(index, parameterType, dependency); } diff --git a/Source/Mockolate/Internals/GenericMethodSetup.cs b/Source/Mockolate/Internals/GenericMethodSetup.cs index 9235f652c..0598e0ae4 100644 --- a/Source/Mockolate/Internals/GenericMethodSetup.cs +++ b/Source/Mockolate/Internals/GenericMethodSetup.cs @@ -298,7 +298,7 @@ IGenericMethodSetup IGenericMethodSetupReturnWhenBuilder.Only(int times) [DebuggerNonUserCode] #endif public sealed class GenericMethodSetup : VoidMethodSetup.WithParameterCollection, IMethodSetupForAnyTypeArguments, - IGenericMethodSetupCallbackBuilder, IGenericMethodSetupReturnBuilder + IGenericMethodParameterTypes, IGenericMethodSetupCallbackBuilder, IGenericMethodSetupReturnBuilder { private readonly Func? _isCallOf; @@ -314,8 +314,17 @@ public GenericMethodSetup(MockRegistry mockRegistry, string name, protected override bool MatchesInteraction(IMethodInteraction interaction) => GenericMethodInvocations.TryGetInvocation(interaction, Name, 1, _isCallOf, out IMethodInvocationParameters invocation) && GenericMethodInvocations.TryGetValue(invocation, 0, out T1 p1Value) && + GenericMethodInvocations.MatchesType(Parameter1, invocation, 0) && Matches(p1Value); + /// + bool IGenericMethodParameterTypes.MatchesParameterType(int index, Type parameterType, ParameterTypeDependency dependency) + => index switch + { + 0 => GenericMethodInvocations.MatchesType(Parameter1, parameterType, dependency), + _ => true, + }; + /// IGenericMethodSetup IGenericMethodSetup.SkippingBaseClass(bool skipBaseClass) { @@ -599,7 +608,7 @@ IGenericMethodSetup IGenericMethodSetupReturnWhenBuilder.Only(in [DebuggerNonUserCode] #endif public sealed class GenericMethodSetup : VoidMethodSetup.WithParameterCollection, IMethodSetupForAnyTypeArguments, - IGenericMethodSetupCallbackBuilder, IGenericMethodSetupReturnBuilder + IGenericMethodParameterTypes, IGenericMethodSetupCallbackBuilder, IGenericMethodSetupReturnBuilder { private readonly Func? _isCallOf; @@ -616,8 +625,19 @@ protected override bool MatchesInteraction(IMethodInteraction interaction) => GenericMethodInvocations.TryGetInvocation(interaction, Name, 2, _isCallOf, out IMethodInvocationParameters invocation) && GenericMethodInvocations.TryGetValue(invocation, 0, out T1 p1Value) && GenericMethodInvocations.TryGetValue(invocation, 1, out T2 p2Value) && + GenericMethodInvocations.MatchesType(Parameter1, invocation, 0) && + GenericMethodInvocations.MatchesType(Parameter2, invocation, 1) && Matches(p1Value, p2Value); + /// + bool IGenericMethodParameterTypes.MatchesParameterType(int index, Type parameterType, ParameterTypeDependency dependency) + => index switch + { + 0 => GenericMethodInvocations.MatchesType(Parameter1, parameterType, dependency), + 1 => GenericMethodInvocations.MatchesType(Parameter2, parameterType, dependency), + _ => true, + }; + /// IGenericMethodSetup IGenericMethodSetup.SkippingBaseClass(bool skipBaseClass) { @@ -902,7 +922,7 @@ IGenericMethodSetup IGenericMethodSetupReturnWhenBuilder [DebuggerNonUserCode] #endif public sealed class GenericMethodSetup : VoidMethodSetup.WithParameterCollection, IMethodSetupForAnyTypeArguments, - IGenericMethodSetupCallbackBuilder, IGenericMethodSetupReturnBuilder + IGenericMethodParameterTypes, IGenericMethodSetupCallbackBuilder, IGenericMethodSetupReturnBuilder { private readonly Func? _isCallOf; @@ -920,8 +940,21 @@ protected override bool MatchesInteraction(IMethodInteraction interaction) GenericMethodInvocations.TryGetValue(invocation, 0, out T1 p1Value) && GenericMethodInvocations.TryGetValue(invocation, 1, out T2 p2Value) && GenericMethodInvocations.TryGetValue(invocation, 2, out T3 p3Value) && + GenericMethodInvocations.MatchesType(Parameter1, invocation, 0) && + GenericMethodInvocations.MatchesType(Parameter2, invocation, 1) && + GenericMethodInvocations.MatchesType(Parameter3, invocation, 2) && Matches(p1Value, p2Value, p3Value); + /// + bool IGenericMethodParameterTypes.MatchesParameterType(int index, Type parameterType, ParameterTypeDependency dependency) + => index switch + { + 0 => GenericMethodInvocations.MatchesType(Parameter1, parameterType, dependency), + 1 => GenericMethodInvocations.MatchesType(Parameter2, parameterType, dependency), + 2 => GenericMethodInvocations.MatchesType(Parameter3, parameterType, dependency), + _ => true, + }; + /// IGenericMethodSetup IGenericMethodSetup.SkippingBaseClass(bool skipBaseClass) { @@ -1207,7 +1240,7 @@ IGenericMethodSetup IGenericMethodSetupReturnWhenBuilder : VoidMethodSetup.WithParameterCollection, IMethodSetupForAnyTypeArguments, - IGenericMethodSetupCallbackBuilder, IGenericMethodSetupReturnBuilder + IGenericMethodParameterTypes, IGenericMethodSetupCallbackBuilder, IGenericMethodSetupReturnBuilder { private readonly Func? _isCallOf; @@ -1227,8 +1260,23 @@ protected override bool MatchesInteraction(IMethodInteraction interaction) GenericMethodInvocations.TryGetValue(invocation, 1, out T2 p2Value) && GenericMethodInvocations.TryGetValue(invocation, 2, out T3 p3Value) && GenericMethodInvocations.TryGetValue(invocation, 3, out T4 p4Value) && + GenericMethodInvocations.MatchesType(Parameter1, invocation, 0) && + GenericMethodInvocations.MatchesType(Parameter2, invocation, 1) && + GenericMethodInvocations.MatchesType(Parameter3, invocation, 2) && + GenericMethodInvocations.MatchesType(Parameter4, invocation, 3) && Matches(p1Value, p2Value, p3Value, p4Value); + /// + bool IGenericMethodParameterTypes.MatchesParameterType(int index, Type parameterType, ParameterTypeDependency dependency) + => index switch + { + 0 => GenericMethodInvocations.MatchesType(Parameter1, parameterType, dependency), + 1 => GenericMethodInvocations.MatchesType(Parameter2, parameterType, dependency), + 2 => GenericMethodInvocations.MatchesType(Parameter3, parameterType, dependency), + 3 => GenericMethodInvocations.MatchesType(Parameter4, parameterType, dependency), + _ => true, + }; + /// IGenericMethodSetup IGenericMethodSetup.SkippingBaseClass(bool skipBaseClass) { diff --git a/Source/Mockolate/Internals/IGenericMethodParameterTypes.cs b/Source/Mockolate/Internals/IGenericMethodParameterTypes.cs new file mode 100644 index 000000000..2abf0f914 --- /dev/null +++ b/Source/Mockolate/Internals/IGenericMethodParameterTypes.cs @@ -0,0 +1,22 @@ +using System; +using System.ComponentModel; + +namespace Mockolate.Internals; + +/// +/// A setup of a generic method for any type argument whose matchers select the type arguments of the calls they +/// match, see . +/// +/// +/// This type is public only so that generated code can use it; it is not intended to be used directly. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +public interface IGenericMethodParameterTypes +{ + /// + /// Checks whether the matcher of the parameter at the zero-based matches a call in which + /// the parameter has the type , which depends on a type argument as + /// tells. + /// + bool MatchesParameterType(int index, Type parameterType, ParameterTypeDependency dependency); +} diff --git a/Source/Mockolate/Internals/ITypedParameter.cs b/Source/Mockolate/Internals/ITypedParameter.cs new file mode 100644 index 000000000..b9d2b9fd8 --- /dev/null +++ b/Source/Mockolate/Internals/ITypedParameter.cs @@ -0,0 +1,15 @@ +using System; + +namespace Mockolate.Internals; + +/// +/// A built-in matcher that tells the type argument of the it implements, +/// which could otherwise only find with reflection that is not trim-safe. +/// +internal interface ITypedParameter +{ + /// + /// The type argument of the that the matcher implements. + /// + Type ParameterType { get; } +} diff --git a/Source/Mockolate/Internals/LiteralParameterMatch.cs b/Source/Mockolate/Internals/LiteralParameterMatch.cs index b0fba1df7..627acd654 100644 --- a/Source/Mockolate/Internals/LiteralParameterMatch.cs +++ b/Source/Mockolate/Internals/LiteralParameterMatch.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.ComponentModel; using Mockolate.Parameters; @@ -18,10 +19,13 @@ namespace Mockolate.Internals; [System.Diagnostics.DebuggerNonUserCode] #endif [EditorBrowsable(EditorBrowsableState.Never)] -public sealed class LiteralParameterMatch : IParameter, IParameterMatch +public sealed class LiteralParameterMatch : IParameter, IParameterMatch, ITypedParameter { private readonly T _value; + /// + Type ITypedParameter.ParameterType => typeof(T); + /// /// Initializes a new for the expected . /// diff --git a/Source/Mockolate/Internals/ParameterTypeDependency.cs b/Source/Mockolate/Internals/ParameterTypeDependency.cs new file mode 100644 index 000000000..09e2eef20 --- /dev/null +++ b/Source/Mockolate/Internals/ParameterTypeDependency.cs @@ -0,0 +1,31 @@ +using System.ComponentModel; + +namespace Mockolate.Internals; + +/// +/// How the type of a parameter of a called generic method depends on its type arguments, which decides how a +/// checks it. +/// +/// +/// This type is public only so that generated code can use it; it is not intended to be used directly. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +public enum ParameterTypeDependency +{ + /// + /// The type of the parameter does not depend on a type argument, e.g. object value of an overload that + /// shares a setup with T value: only the value is checked. + /// + Independent, + + /// + /// The type of the parameter is a type parameter, e.g. T value. + /// + TypeParameter, + + /// + /// The type of the parameter only partly depends on a type argument, e.g. IRequest<T> request or + /// T? value of a value type T. + /// + PartlyDependent, +} diff --git a/Source/Mockolate/Internals/TypeArgumentParameterMatch.cs b/Source/Mockolate/Internals/TypeArgumentParameterMatch.cs new file mode 100644 index 000000000..1d304a505 --- /dev/null +++ b/Source/Mockolate/Internals/TypeArgumentParameterMatch.cs @@ -0,0 +1,166 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using Mockolate.Parameters; + +namespace Mockolate.Internals; + +/// +/// The matcher of a parameter whose type depends on a type argument, in a setup or verification of a generic method +/// for any type argument. The type of the matcher selects the type arguments of the calls it matches, and the +/// matcher then checks the value of the call. +/// +/// +/// A call matches when the type that the parameter has in the call, e.g. for a parameter +/// T value of a call Write<string>(…), converts to the type of the matcher: it is the same type, +/// derives from it or implements it, or is boxed to it, so a matcher of matches every type +/// argument. When the parameter type only partly depends on a type argument, e.g. IRequest<T> or +/// T? of a value type T, a call also matches when the type of the matcher is the underlying type of +/// that nullable value type, or implements or derives from the parameter type exactly, e.g. a matcher of +/// Ping : IRequest<int> matches the calls with IRequest<int> but not those with +/// IRequest<object>. When the parameter does not depend on a type argument in the called overload, +/// only the value is checked. +/// +/// This type is public only so that generated code can use it; it is not intended to be used directly. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +#if !DEBUG +[DebuggerNonUserCode] +#endif +public sealed class TypeArgumentParameterMatch : IParameterMatch +{ + private readonly IParameter _parameter; + private readonly ParameterTypeDependency _dependency; + private readonly Func? _dependencyOf; + private TypeCheck? _lastTypeCheck; + + private TypeArgumentParameterMatch(IParameter parameter, Type matcherType, ParameterTypeDependency dependency, + Func? dependencyOf) + { + _parameter = parameter; + MatcherType = matcherType; + _dependency = dependency; + _dependencyOf = dependencyOf; + } + + /// + /// The type of the matcher, which selects the type arguments of the calls it matches. + /// + public Type MatcherType { get; } + + /// + public bool Matches(object? value) + => _parameter.Matches(value); + + /// + public void InvokeCallbacks(object? value) + => _parameter.InvokeCallbacks(value); + + /// + /// Creates the matcher from a of the type , or from + /// , which matches a argument of the type . + /// + /// The matcher, or . + /// How the type of the parameter depends on a type argument in a recorded call. + /// + /// Tells, for the setups and verifications of overloads that differ in it, how the type of the parameter depends + /// on a type argument in a recorded call; when it is always . + /// + public static TypeArgumentParameterMatch Create(IParameter? parameter, ParameterTypeDependency dependency, + Func? dependencyOf = null) + => new(parameter ?? Matchers.IsNull(), typeof(T), dependency, dependencyOf); + + /// + /// Creates the matcher from a whose type is the type argument of the + /// that a built-in matcher implements, or for any other + /// matcher, or from , which matches a argument of any type argument. + /// + /// The matcher, or . + /// How the type of the parameter depends on a type argument in a recorded call. + /// + /// Tells, for the setups and verifications of overloads that differ in it, how the type of the parameter depends + /// on a type argument in a recorded call; when it is always . + /// + public static TypeArgumentParameterMatch Create(IParameter? parameter, ParameterTypeDependency dependency, + Func? dependencyOf = null) + => parameter is null + ? new TypeArgumentParameterMatch(Matchers.IsNull(), typeof(object), dependency, dependencyOf) + : new TypeArgumentParameterMatch(parameter, GetMatcherType(parameter), dependency, dependencyOf); + + /// + /// Checks whether the recorded call , whose parameter at the zero-based + /// this matcher matches, has the type arguments that the type of the matcher selects. + /// + public bool MatchesType(IMethodInvocationParameters invocation, int index) + => MatchesType(invocation.GetParameterTypeAt(index), _dependencyOf?.Invoke(invocation) ?? _dependency); + + /// + /// Checks whether a call whose parameter has the type has the type arguments + /// that the type of the matcher selects. + /// + /// The type of the parameter in the call, or when it is unknown, which matches. + /// How the type of the parameter depends on a type argument in the called overload. + public bool MatchesType(Type? parameterType, ParameterTypeDependency dependency) + { + if (parameterType is null || dependency == ParameterTypeDependency.Independent || + MatcherType == typeof(object)) + { + return true; + } + + TypeCheck? lastTypeCheck = _lastTypeCheck; + if (lastTypeCheck is not null && lastTypeCheck.ParameterType == parameterType && + lastTypeCheck.Dependency == dependency) + { + return lastTypeCheck.Result; + } + + bool result = IsImplicitlyConvertible(parameterType, MatcherType) || + (dependency == ParameterTypeDependency.PartlyDependent && + (Nullable.GetUnderlyingType(parameterType) == MatcherType || + IsBaseTypeOrInterface(parameterType, MatcherType))); + _lastTypeCheck = new TypeCheck(parameterType, dependency, result); + return result; + } + + /// + public override string? ToString() + => _parameter.ToString(); + + /// + /// An identity, reference (also a variant one), boxing or nullable conversion. + /// + private static bool IsImplicitlyConvertible(Type from, Type to) + => to.IsAssignableFrom(from) || + (!to.IsValueType && Nullable.GetUnderlyingType(from) is { } underlyingType && + to.IsAssignableFrom(underlyingType)); + + /// + /// Whether is , one of its base types or one of its + /// interfaces, so that the type arguments of follow from . + /// + /// + /// Listing the interfaces of is not trim-safe, so a variant conversion also counts: a + /// matcher of Ping : IRequest<string> also matches the calls with IRequest<object> of a + /// covariant IRequest<out T>. + /// + private static bool IsBaseTypeOrInterface(Type baseType, Type type) + => baseType.IsAssignableFrom(type); + + /// + /// The type argument of the that a built-in matcher implements, or + /// for any other matcher, as finding it would need reflection that is not trim-safe. + /// + private static Type GetMatcherType(IParameter parameter) + => parameter is ITypedParameter typedParameter ? typedParameter.ParameterType : typeof(object); + + /// + /// The result of the last check of a parameter type, as a matcher mostly sees calls of the same type arguments. + /// + private sealed class TypeCheck(Type parameterType, ParameterTypeDependency dependency, bool result) + { + public Type ParameterType { get; } = parameterType; + public ParameterTypeDependency Dependency { get; } = dependency; + public bool Result { get; } = result; + } +} diff --git a/Source/Mockolate/It.cs b/Source/Mockolate/It.cs index a9918a187..ba987ac8c 100644 --- a/Source/Mockolate/It.cs +++ b/Source/Mockolate/It.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using Mockolate.Internals; using Mockolate.Parameters; namespace Mockolate; @@ -56,11 +57,14 @@ private It() #if !DEBUG [System.Diagnostics.DebuggerNonUserCode] #endif - internal abstract class TypedMatch : IParameterWithCallback, IParameterMatch + internal abstract class TypedMatch : IParameterWithCallback, IParameterMatch, ITypedParameter { private List>? _callbacks; private bool _isShared; + /// + Type ITypedParameter.ParameterType => typeof(T); + /// /// Whether the instance is a cached singleton that callbacks are never added to; Do adds them to a copy /// instead. diff --git a/Tests/Mockolate.SourceGenerators.Tests/Emission/MethodEmissionTests.cs b/Tests/Mockolate.SourceGenerators.Tests/Emission/MethodEmissionTests.cs index 8131cb0e4..76e64b438 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Emission/MethodEmissionTests.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Emission/MethodEmissionTests.cs @@ -208,6 +208,88 @@ await That(result.Sources["Mock.ISender.g.cs"]) .Because("the overloads keep their other setups"); } + [Test] + public async Task SetupGeneric_ShouldCheckTheTypesOfTheParametersThatDependOnATypeArgument() + { + GeneratorResult result = Generator + .Run(""" + #nullable enable + using System.Collections.Generic; + using Mockolate; + + namespace MyCode; + public class Program + { + public static void Main(string[] args) + { + _ = IMyService.CreateMock(); + } + } + + public interface IMyService + { + void Write(T value, int count); + void Maybe(T? value); + void Struct(T? value) where T : struct; + void Many(IEnumerable values); + } + """); + + await That(result.Diagnostics).IsEmpty(); + await That(result.Sources["Mock.IMyService.g.cs"]) + .Contains("global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(g_methodSetup, 0, typeof(T), global::Mockolate.Internals.ParameterTypeDependency.TypeParameter) && g_methodSetup.Matches((object?)value, count)").And + .Contains("global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(g_methodSetup, 0, typeof(T), global::Mockolate.Internals.ParameterTypeDependency.TypeParameter) && g_methodSetup.Matches((object?)value)").And + .Contains("global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(g_methodSetup, 0, typeof(T?), global::Mockolate.Internals.ParameterTypeDependency.PartlyDependent) && g_methodSetup.Matches((object?)value)").And + .Contains("global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(g_methodSetup, 0, typeof(global::System.Collections.Generic.IEnumerable), global::Mockolate.Internals.ParameterTypeDependency.PartlyDependent) && g_methodSetup.Matches((object?)values)").And + .Contains("global::Mockolate.Internals.TypeArgumentParameterMatch.Create(value, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter), global::Mockolate.CovariantParameterAdapter.Wrap(").And + .Contains("global::Mockolate.Internals.TypeArgumentParameterMatch.Create(value, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)").And + .Contains("global::Mockolate.Internals.TypeArgumentParameterMatch.Create(values, global::Mockolate.Internals.ParameterTypeDependency.PartlyDependent)").And + .Contains("global::Mockolate.Internals.TypeArgumentParameterMatch.Create(values, global::Mockolate.Internals.ParameterTypeDependency.PartlyDependent)").And + .Contains("\"global::MyCode.IMyService.Struct<>\", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(value, global::Mockolate.Internals.ParameterTypeDependency.PartlyDependent)") + .Because("T? of a value type T is a Nullable, which only partly depends on the type argument").And + .Contains("\"global::MyCode.IMyService.Maybe<>\", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(value, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)") + .Because("T? of an unconstrained T is the type argument itself"); + } + + [Test] + public async Task SetupGeneric_WithOverloadsWhoseParametersDependDifferently_ShouldRecognizeTheOverloadOfARecordedCall() + { + GeneratorResult result = Generator + .Run(""" + using Mockolate; + + namespace MyCode; + public class Program + { + public static void Main(string[] args) + { + _ = IMyService.CreateMock(); + } + } + + public interface IRequest; + public interface IMyService + { + void Send(IRequest request); + void Send(TRequest request); + void Overloaded(T value); + void Overloaded(object value); + } + """); + + await That(result.Diagnostics).IsEmpty(); + await That(result.Sources["Mock.IMyService.g.cs"]) + .Contains("global::Mockolate.Internals.TypeArgumentParameterMatch.Create(request, global::Mockolate.Internals.ParameterTypeDependency.PartlyDependent, static invocation => global::Mockolate.Internals.GenericMethodInvocations.IsTypeArgument(invocation, 0, 0) ? global::Mockolate.Internals.ParameterTypeDependency.TypeParameter : global::Mockolate.Internals.ParameterTypeDependency.PartlyDependent)").And + .Contains("global::Mockolate.Internals.TypeArgumentParameterMatch.Create(value, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter, static invocation => invocation.GetParameterTypeAt(0) == typeof(object) ? global::Mockolate.Internals.ParameterTypeDependency.Independent : global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)") + .Because("a call that both overloads could have made is one of the overload whose parameter does not depend on a type argument"); + await That(result.Sources["Mock.IMyService.g.cs"]) + .Contains("global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(g_methodSetup, 0, typeof(T), typeof(T) == typeof(object) ? global::Mockolate.Internals.ParameterTypeDependency.Independent : global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)") + .Because("a call of Overloaded(T value) is recorded like one of Overloaded(object value)").And + .Contains("global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(g_methodSetup, 0, typeof(TRequest), global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)").And + .Contains("global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(g_methodSetup, 0, typeof(global::MyCode.IRequest), typeof(global::MyCode.IRequest) == typeof(TResponse) ? global::Mockolate.Internals.ParameterTypeDependency.TypeParameter : global::Mockolate.Internals.ParameterTypeDependency.PartlyDependent)"); + + } + [Test] public async Task SetupGeneric_ShouldOfferOverloadsThatShareTheSignatureOnlyWhenTheyShareTheParameterNames() { diff --git a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs index f0da48ea1..1cebf73b0 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs @@ -434,7 +434,7 @@ public override void Log(global::Microsoft.Extensions.Logging.LogLevel l /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForConcreteLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ConcreteLogger.MemberId_BeginScope_TState_, methodSetup); return methodSetup; } @@ -442,7 +442,7 @@ public override void Log(global::Microsoft.Extensions.Logging.LogLevel l /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForConcreteLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ConcreteLogger.MemberId_BeginScope_TState_, methodSetup); return methodSetup; } @@ -458,14 +458,14 @@ public override void Log(global::Microsoft.Extensions.Logging.LogLevel l /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForConcreteLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForConcreteLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } @@ -590,14 +590,14 @@ private sealed class VerifyMonitorConcreteLogger(global::Mockolate.Internals.Moc /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForConcreteLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForConcreteLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } @@ -763,7 +763,7 @@ public MockInScenarioForConcreteLogger(global::Mockolate.Internals.MockRegistry /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForConcreteLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ConcreteLogger.MemberId_BeginScope_TState_, this._scenarioName, methodSetup); return methodSetup; } @@ -771,7 +771,7 @@ public MockInScenarioForConcreteLogger(global::Mockolate.Internals.MockRegistry /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForConcreteLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.AbstractLoggerBase.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ConcreteLogger.MemberId_BeginScope_TState_, this._scenarioName, methodSetup); return methodSetup; } @@ -1952,7 +1952,7 @@ public override void Log(global::Microsoft.Extensions.Logging.LogLevel l /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForLeafLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.LeafLogger.MemberId_BeginScope_TState_, methodSetup); return methodSetup; } @@ -1960,7 +1960,7 @@ public override void Log(global::Microsoft.Extensions.Logging.LogLevel l /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForLeafLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.LeafLogger.MemberId_BeginScope_TState_, methodSetup); return methodSetup; } @@ -1976,14 +1976,14 @@ public override void Log(global::Microsoft.Extensions.Logging.LogLevel l /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForLeafLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForLeafLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } @@ -2108,14 +2108,14 @@ private sealed class VerifyMonitorLeafLogger(global::Mockolate.Internals.MockReg /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForLeafLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForLeafLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } @@ -2281,7 +2281,7 @@ public MockInScenarioForLeafLogger(global::Mockolate.Internals.MockRegistry mock /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForLeafLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.LeafLogger.MemberId_BeginScope_TState_, this._scenarioName, methodSetup); return methodSetup; } @@ -2289,7 +2289,7 @@ public MockInScenarioForLeafLogger(global::Mockolate.Internals.MockRegistry mock /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForLeafLogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Mockolate.Tests.GeneratorCoverage.VirtualLoggerBase.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.LeafLogger.MemberId_BeginScope_TState_, this._scenarioName, methodSetup); return methodSetup; } diff --git a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging.LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging.LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs index aac29621b..6466f9abe 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging.LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging.LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs @@ -1092,7 +1092,7 @@ bool IsMatchingSetup(global::Mockolate.Setup.MethodSetup candidate) { ScopeSetup scopeCandidate => scopeCandidate.MatchesScope(invocation), global::Mockolate.Setup.ReturnMethodSetup typedSetup => typedSetup.Name == name && typedSetup.Matches(state), - global::Mockolate.Setup.VoidMethodSetup anyTypeCandidate => anyTypeCandidate.Name == anyTypeName && anyTypeCandidate.Matches(state), + global::Mockolate.Setup.VoidMethodSetup anyTypeCandidate => anyTypeCandidate.Name == anyTypeName && global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(anyTypeCandidate, 0, typeof(TState), global::Mockolate.Internals.ParameterTypeDependency.TypeParameter) && anyTypeCandidate.Matches(state), _ => false, }; diff --git a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging.Logging_CanBeCreated.g.awexpect-snapshot.cs b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging.Logging_CanBeCreated.g.awexpect-snapshot.cs index 15784fc70..ff162d8d5 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging.Logging_CanBeCreated.g.awexpect-snapshot.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging.Logging_CanBeCreated.g.awexpect-snapshot.cs @@ -1092,7 +1092,7 @@ bool IsMatchingSetup(global::Mockolate.Setup.MethodSetup candidate) { ScopeSetup scopeCandidate => scopeCandidate.MatchesScope(invocation), global::Mockolate.Setup.ReturnMethodSetup typedSetup => typedSetup.Name == name && typedSetup.Matches(state), - global::Mockolate.Setup.VoidMethodSetup anyTypeCandidate => anyTypeCandidate.Name == anyTypeName && anyTypeCandidate.Matches(state), + global::Mockolate.Setup.VoidMethodSetup anyTypeCandidate => anyTypeCandidate.Name == anyTypeName && global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(anyTypeCandidate, 0, typeof(TState), global::Mockolate.Internals.ParameterTypeDependency.TypeParameter) && anyTypeCandidate.Matches(state), _ => false, }; diff --git a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging_CanBeCreated.g.awexpect-snapshot.cs b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging_CanBeCreated.g.awexpect-snapshot.cs index 46e0d45ca..80885d58b 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging_CanBeCreated.g.awexpect-snapshot.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/Logging_CanBeCreated.g.awexpect-snapshot.cs @@ -424,7 +424,7 @@ public bool IsEnabled(global::Microsoft.Extensions.Logging.LogLevel logLevel) /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForILogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ILogger.MemberId_BeginScope_TState_, methodSetup); return methodSetup; } @@ -432,7 +432,7 @@ public bool IsEnabled(global::Microsoft.Extensions.Logging.LogLevel logLevel) /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForILogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ILogger.MemberId_BeginScope_TState_, methodSetup); return methodSetup; } @@ -448,14 +448,14 @@ public bool IsEnabled(global::Microsoft.Extensions.Logging.LogLevel logLevel) /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForILogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForILogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } @@ -580,14 +580,14 @@ private sealed class VerifyMonitorILogger(global::Mockolate.Internals.MockRegist /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForILogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForILogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } @@ -753,7 +753,7 @@ public MockInScenarioForILogger(global::Mockolate.Internals.MockRegistry mockReg /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForILogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ILogger.MemberId_BeginScope_TState_, this._scenarioName, methodSetup); return methodSetup; } @@ -761,7 +761,7 @@ public MockInScenarioForILogger(global::Mockolate.Internals.MockRegistry mockReg /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForILogger.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ILogger.MemberId_BeginScope_TState_, this._scenarioName, methodSetup); return methodSetup; } @@ -2823,7 +2823,7 @@ public bool IsEnabled(global::Microsoft.Extensions.Logging.LogLevel logLevel) /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForILogger_Program.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ILogger_Program.MemberId_BeginScope_TState_, methodSetup); return methodSetup; } @@ -2831,7 +2831,7 @@ public bool IsEnabled(global::Microsoft.Extensions.Logging.LogLevel logLevel) /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForILogger_Program.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ILogger_Program.MemberId_BeginScope_TState_, methodSetup); return methodSetup; } @@ -2847,14 +2847,14 @@ public bool IsEnabled(global::Microsoft.Extensions.Logging.LogLevel logLevel) /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForILogger_Program.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForILogger_Program.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } @@ -2979,14 +2979,14 @@ private sealed class VerifyMonitorILogger_Program(global::Mockolate.Internals.Mo /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForILogger_Program.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } /// global::Mockolate.Verify.VerificationResult IMockGenericVerifyForILogger_Program.BeginScope(global::Mockolate.Parameters.IParameter? state) { - global::Mockolate.Parameters.IParameterMatch match1 = new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull()); + global::Mockolate.Parameters.IParameterMatch match1 = global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter); return this.MockRegistry.VerifyGenericMethod(this, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", 1, null, invocation => global::Mockolate.Internals.GenericMethodInvocations.Matches(match1, invocation, 0), () => $"BeginScope({(global::Mockolate.Internals.ValueFormatter.Format((object?)state))})"); } @@ -3152,7 +3152,7 @@ public MockInScenarioForILogger_Program(global::Mockolate.Internals.MockRegistry /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForILogger_Program.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter(state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ILogger_Program.MemberId_BeginScope_TState_, this._scenarioName, methodSetup); return methodSetup; } @@ -3160,7 +3160,7 @@ public MockInScenarioForILogger_Program(global::Mockolate.Internals.MockRegistry /// global::Mockolate.Setup.IGenericMethodSetup IMockGenericSetupForILogger_Program.BeginScope(global::Mockolate.Parameters.IParameter? state) { - var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, new global::Mockolate.CovariantParameterAdapter((global::Mockolate.Parameters.IParameter?)state ?? global::Mockolate.Internals.Matchers.IsNull())); + var methodSetup = new global::Mockolate.Internals.GenericMethodSetup(this.MockRegistry, "global::Microsoft.Extensions.Logging.ILogger.BeginScope<>", null, global::Mockolate.Internals.TypeArgumentParameterMatch.Create(state, global::Mockolate.Internals.ParameterTypeDependency.TypeParameter)); this.MockRegistry.SetupMethod(global::Mockolate.Mock.ILogger_Program.MemberId_BeginScope_TState_, this._scenarioName, methodSetup); return methodSetup; } diff --git a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.ComprehensiveInterface_CanBeCreated.g.awexpect-snapshot.cs b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.ComprehensiveInterface_CanBeCreated.g.awexpect-snapshot.cs index 9a792519e..19f663acf 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.ComprehensiveInterface_CanBeCreated.g.awexpect-snapshot.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.ComprehensiveInterface_CanBeCreated.g.awexpect-snapshot.cs @@ -3933,7 +3933,7 @@ protected override bool MatchesInteraction(global::Mockolate.Interactions.IMetho /// Setup for a generic method with 5 parameters, for any type argument, matching against individual IParameterMatch<T>. [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - internal sealed class GenericMethodSetup : global::Mockolate.Setup.VoidMethodSetup.WithParameterCollection, global::Mockolate.Internals.IMethodSetupForAnyTypeArguments, + internal sealed class GenericMethodSetup : global::Mockolate.Setup.VoidMethodSetup.WithParameterCollection, global::Mockolate.Internals.IMethodSetupForAnyTypeArguments, global::Mockolate.Internals.IGenericMethodParameterTypes, global::Mockolate.Setup.IGenericMethodSetupCallbackBuilder, global::Mockolate.Setup.IGenericMethodSetupReturnBuilder { private readonly global::System.Func? _isCallOf; @@ -3953,8 +3953,25 @@ protected override bool MatchesInteraction(global::Mockolate.Interactions.IMetho global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 2, out T3 p3Value) && global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 3, out T4 p4Value) && global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 4, out T5 p5Value) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter1, invocation, 0) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter2, invocation, 1) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter3, invocation, 2) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter4, invocation, 3) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter5, invocation, 4) && Matches(p1Value, p2Value, p3Value, p4Value, p5Value); + /// + bool global::Mockolate.Internals.IGenericMethodParameterTypes.MatchesParameterType(int index, global::System.Type parameterType, global::Mockolate.Internals.ParameterTypeDependency dependency) + => index switch + { + 0 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter1, parameterType, dependency), + 1 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter2, parameterType, dependency), + 2 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter3, parameterType, dependency), + 3 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter4, parameterType, dependency), + 4 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter5, parameterType, dependency), + _ => true, + }; + /// global::Mockolate.Setup.IGenericMethodSetup global::Mockolate.Setup.IGenericMethodSetup.SkippingBaseClass(bool skipBaseClass) { @@ -4223,7 +4240,7 @@ protected override bool MatchesInteraction(global::Mockolate.Interactions.IMetho /// Setup for a generic method with 7 parameters, for any type argument, matching against individual IParameterMatch<T>. [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - internal sealed class GenericMethodSetup : global::Mockolate.Setup.VoidMethodSetup.WithParameterCollection, global::Mockolate.Internals.IMethodSetupForAnyTypeArguments, + internal sealed class GenericMethodSetup : global::Mockolate.Setup.VoidMethodSetup.WithParameterCollection, global::Mockolate.Internals.IMethodSetupForAnyTypeArguments, global::Mockolate.Internals.IGenericMethodParameterTypes, global::Mockolate.Setup.IGenericMethodSetupCallbackBuilder, global::Mockolate.Setup.IGenericMethodSetupReturnBuilder { private readonly global::System.Func? _isCallOf; @@ -4245,8 +4262,29 @@ protected override bool MatchesInteraction(global::Mockolate.Interactions.IMetho global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 4, out T5 p5Value) && global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 5, out T6 p6Value) && global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 6, out T7 p7Value) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter1, invocation, 0) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter2, invocation, 1) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter3, invocation, 2) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter4, invocation, 3) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter5, invocation, 4) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter6, invocation, 5) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter7, invocation, 6) && Matches(p1Value, p2Value, p3Value, p4Value, p5Value, p6Value, p7Value); + /// + bool global::Mockolate.Internals.IGenericMethodParameterTypes.MatchesParameterType(int index, global::System.Type parameterType, global::Mockolate.Internals.ParameterTypeDependency dependency) + => index switch + { + 0 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter1, parameterType, dependency), + 1 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter2, parameterType, dependency), + 2 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter3, parameterType, dependency), + 3 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter4, parameterType, dependency), + 4 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter5, parameterType, dependency), + 5 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter6, parameterType, dependency), + 6 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter7, parameterType, dependency), + _ => true, + }; + /// global::Mockolate.Setup.IGenericMethodSetup global::Mockolate.Setup.IGenericMethodSetup.SkippingBaseClass(bool skipBaseClass) { @@ -4525,7 +4563,7 @@ protected override bool MatchesInteraction(global::Mockolate.Interactions.IMetho /// Setup for a generic method with 17 parameters, for any type argument, matching against individual IParameterMatch<T>. [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - internal sealed class GenericMethodSetup : global::Mockolate.Setup.VoidMethodSetup.WithParameterCollection, global::Mockolate.Internals.IMethodSetupForAnyTypeArguments, + internal sealed class GenericMethodSetup : global::Mockolate.Setup.VoidMethodSetup.WithParameterCollection, global::Mockolate.Internals.IMethodSetupForAnyTypeArguments, global::Mockolate.Internals.IGenericMethodParameterTypes, global::Mockolate.Setup.IGenericMethodSetupCallbackBuilder, global::Mockolate.Setup.IGenericMethodSetupReturnBuilder { private readonly global::System.Func? _isCallOf; @@ -4557,8 +4595,49 @@ protected override bool MatchesInteraction(global::Mockolate.Interactions.IMetho global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 14, out T15 p15Value) && global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 15, out T16 p16Value) && global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 16, out T17 p17Value) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter1, invocation, 0) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter2, invocation, 1) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter3, invocation, 2) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter4, invocation, 3) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter5, invocation, 4) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter6, invocation, 5) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter7, invocation, 6) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter8, invocation, 7) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter9, invocation, 8) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter10, invocation, 9) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter11, invocation, 10) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter12, invocation, 11) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter13, invocation, 12) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter14, invocation, 13) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter15, invocation, 14) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter16, invocation, 15) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter17, invocation, 16) && Matches(p1Value, p2Value, p3Value, p4Value, p5Value, p6Value, p7Value, p8Value, p9Value, p10Value, p11Value, p12Value, p13Value, p14Value, p15Value, p16Value, p17Value); + /// + bool global::Mockolate.Internals.IGenericMethodParameterTypes.MatchesParameterType(int index, global::System.Type parameterType, global::Mockolate.Internals.ParameterTypeDependency dependency) + => index switch + { + 0 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter1, parameterType, dependency), + 1 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter2, parameterType, dependency), + 2 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter3, parameterType, dependency), + 3 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter4, parameterType, dependency), + 4 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter5, parameterType, dependency), + 5 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter6, parameterType, dependency), + 6 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter7, parameterType, dependency), + 7 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter8, parameterType, dependency), + 8 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter9, parameterType, dependency), + 9 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter10, parameterType, dependency), + 10 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter11, parameterType, dependency), + 11 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter12, parameterType, dependency), + 12 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter13, parameterType, dependency), + 13 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter14, parameterType, dependency), + 14 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter15, parameterType, dependency), + 15 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter16, parameterType, dependency), + 16 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter17, parameterType, dependency), + _ => true, + }; + /// global::Mockolate.Setup.IGenericMethodSetup global::Mockolate.Setup.IGenericMethodSetup.SkippingBaseClass(bool skipBaseClass) { diff --git a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs index a502ca52e..4888deebc 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.LoggerClasses_CanBeCreated.g.awexpect-snapshot.cs @@ -927,7 +927,7 @@ protected override bool MatchesInteraction(global::Mockolate.Interactions.IMetho /// Setup for a generic method with 5 parameters, for any type argument, matching against individual IParameterMatch<T>. [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - internal sealed class GenericMethodSetup : global::Mockolate.Setup.VoidMethodSetup.WithParameterCollection, global::Mockolate.Internals.IMethodSetupForAnyTypeArguments, + internal sealed class GenericMethodSetup : global::Mockolate.Setup.VoidMethodSetup.WithParameterCollection, global::Mockolate.Internals.IMethodSetupForAnyTypeArguments, global::Mockolate.Internals.IGenericMethodParameterTypes, global::Mockolate.Setup.IGenericMethodSetupCallbackBuilder, global::Mockolate.Setup.IGenericMethodSetupReturnBuilder { private readonly global::System.Func? _isCallOf; @@ -947,8 +947,25 @@ protected override bool MatchesInteraction(global::Mockolate.Interactions.IMetho global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 2, out T3 p3Value) && global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 3, out T4 p4Value) && global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 4, out T5 p5Value) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter1, invocation, 0) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter2, invocation, 1) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter3, invocation, 2) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter4, invocation, 3) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter5, invocation, 4) && Matches(p1Value, p2Value, p3Value, p4Value, p5Value); + /// + bool global::Mockolate.Internals.IGenericMethodParameterTypes.MatchesParameterType(int index, global::System.Type parameterType, global::Mockolate.Internals.ParameterTypeDependency dependency) + => index switch + { + 0 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter1, parameterType, dependency), + 1 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter2, parameterType, dependency), + 2 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter3, parameterType, dependency), + 3 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter4, parameterType, dependency), + 4 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter5, parameterType, dependency), + _ => true, + }; + /// global::Mockolate.Setup.IGenericMethodSetup global::Mockolate.Setup.IGenericMethodSetup.SkippingBaseClass(bool skipBaseClass) { diff --git a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.RefStructConsumer_CanBeCreated.g.awexpect-snapshot.cs b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.RefStructConsumer_CanBeCreated.g.awexpect-snapshot.cs index 79ac65d18..7a5b65f58 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.RefStructConsumer_CanBeCreated.g.awexpect-snapshot.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MethodSetups.RefStructConsumer_CanBeCreated.g.awexpect-snapshot.cs @@ -1506,7 +1506,7 @@ protected override bool MatchesInteraction(global::Mockolate.Interactions.IMetho /// Setup for a generic method with 5 parameters, for any type argument, matching against individual IParameterMatch<T>. [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - internal sealed class GenericMethodSetup : global::Mockolate.Setup.VoidMethodSetup.WithParameterCollection, global::Mockolate.Internals.IMethodSetupForAnyTypeArguments, + internal sealed class GenericMethodSetup : global::Mockolate.Setup.VoidMethodSetup.WithParameterCollection, global::Mockolate.Internals.IMethodSetupForAnyTypeArguments, global::Mockolate.Internals.IGenericMethodParameterTypes, global::Mockolate.Setup.IGenericMethodSetupCallbackBuilder, global::Mockolate.Setup.IGenericMethodSetupReturnBuilder { private readonly global::System.Func? _isCallOf; @@ -1526,8 +1526,25 @@ protected override bool MatchesInteraction(global::Mockolate.Interactions.IMetho global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 2, out T3 p3Value) && global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 3, out T4 p4Value) && global::Mockolate.Internals.GenericMethodInvocations.TryGetValue(invocation, 4, out T5 p5Value) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter1, invocation, 0) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter2, invocation, 1) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter3, invocation, 2) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter4, invocation, 3) && + global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter5, invocation, 4) && Matches(p1Value, p2Value, p3Value, p4Value, p5Value); + /// + bool global::Mockolate.Internals.IGenericMethodParameterTypes.MatchesParameterType(int index, global::System.Type parameterType, global::Mockolate.Internals.ParameterTypeDependency dependency) + => index switch + { + 0 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter1, parameterType, dependency), + 1 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter2, parameterType, dependency), + 2 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter3, parameterType, dependency), + 3 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter4, parameterType, dependency), + 4 => global::Mockolate.Internals.GenericMethodInvocations.MatchesType(Parameter5, parameterType, dependency), + _ => true, + }; + /// global::Mockolate.Setup.IGenericMethodSetup global::Mockolate.Setup.IGenericMethodSetup.SkippingBaseClass(bool skipBaseClass) { diff --git a/Tests/Mockolate.Tests/GeneratorCoverage/IAnyTypeOverloadOrders.cs b/Tests/Mockolate.Tests/GeneratorCoverage/IAnyTypeOverloadOrders.cs new file mode 100644 index 000000000..f1c01ce7f --- /dev/null +++ b/Tests/Mockolate.Tests/GeneratorCoverage/IAnyTypeOverloadOrders.cs @@ -0,0 +1,54 @@ +namespace Mockolate.Tests.GeneratorCoverage; + +/// +/// A request that is also a command, for the overloads of . +/// +public interface IAnyTypeCommand; + +/// +/// Overloads that share a setup for any type argument, whose parameter is a type parameter in one and only partly +/// depends on a type argument in the other, with the type parameter declared first. +/// +public interface IAnyTypeCommandSenderTypeParameterFirst +{ + void Send(TRequest request) where TRequest : IAnyTypeCommand; + void Send(IAnyTypeRequest request); +} + +/// +/// As , in the order of MediatR's ISender. +/// +public interface IAnyTypeCommandSenderRequestFirst +{ + void Send(IAnyTypeRequest request); + void Send(TRequest request) where TRequest : IAnyTypeCommand; +} + +/// +/// Overloads that share a setup for any type argument, whose parameter depends on a type argument in one but not in +/// the other, with the independent one declared first. +/// +public interface IAnyTypeOverloadedIndependentFirst +{ + void Overloaded(object value); + void Overloaded(T value); +} + +/// +/// Overloads that share a setup for any type argument, where one recognizes its calls by more parameter types than +/// the other, with the one that recognizes fewer declared first. +/// +public interface IAnyTypeAddEnumerableFirst +{ + void Add(string key, System.Collections.Generic.IEnumerable value); + void Add(string key, T value); +} + +/// +/// As , with the other order. +/// +public interface IAnyTypeAddTypeParameterFirst +{ + void Add(string key, T value); + void Add(string key, System.Collections.Generic.IEnumerable value); +} diff --git a/Tests/Mockolate.Tests/GeneratorCoverage/IGenericMethodAnyTypeArgument.cs b/Tests/Mockolate.Tests/GeneratorCoverage/IGenericMethodAnyTypeArgument.cs index 4dc5697fb..181c5bb21 100644 --- a/Tests/Mockolate.Tests/GeneratorCoverage/IGenericMethodAnyTypeArgument.cs +++ b/Tests/Mockolate.Tests/GeneratorCoverage/IGenericMethodAnyTypeArgument.cs @@ -6,8 +6,9 @@ namespace Mockolate.Tests.GeneratorCoverage; /// /// Generic methods of every arity, which SetupGeneric and VerifyGeneric offer for any type argument: -/// a parameter that depends on a type argument is matched as , any other keeps its type, and -/// constraints do not apply. Above four parameters the setups are generated, also the setup without a return value +/// a parameter that depends on a type argument takes a matcher of any type, whose type selects the type arguments +/// of the calls it matches, also of a parameter that only partly depends on a type argument, any other keeps its +/// type, and constraints do not apply. Above four parameters the setups are generated, also the setup without a return value /// for a method that returns one. Overloads whose counterparts would share a signature are offered once, but not those /// that differ in a nullable value type, and calls of overloads with another number of type parameters are told /// apart, as are overloads with as many type parameters and parameters, by the types of their parameters. Overloads @@ -56,4 +57,7 @@ public interface IGenericMethodAnyTypeArgument void Described(Exception error); void Listed(T value); void Listed(IEnumerable list); + void Enumerated(IEnumerable values); + void Maybe(T? value); + void NullableOnly(T? value) where T : struct; } diff --git a/Tests/Mockolate.Tests/GeneratorShapes/GenericMethodAnyTypeArgumentTests.TypeArguments.cs b/Tests/Mockolate.Tests/GeneratorShapes/GenericMethodAnyTypeArgumentTests.TypeArguments.cs new file mode 100644 index 000000000..ad3a41b0a --- /dev/null +++ b/Tests/Mockolate.Tests/GeneratorShapes/GenericMethodAnyTypeArgumentTests.TypeArguments.cs @@ -0,0 +1,428 @@ +using System; +using System.Collections.Generic; +using Mockolate.Parameters; +using Mockolate.Setup; +using Mockolate.Tests.GeneratorCoverage; + +namespace Mockolate.Tests.GeneratorShapes; + +public sealed partial class GenericMethodAnyTypeArgumentTests +{ + public sealed class TypeArgumentTests + { + [Test] + public async Task WithANegativeMatcher_ShouldOnlyMatchTheTypeArgumentOfTheMatcher() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + List received = []; + sut.Mock.SetupGeneric.Plain(It.IsNot("a")).Do(value => received.Add(value)); + + sut.Plain("a"); + sut.Plain("b"); + sut.Plain("c"); + sut.Plain(1); + sut.Plain(null); + + await That(received).IsEqualTo(["b", null,]) + .Because("a negative matcher of string does not match the calls with another type argument"); + await That(sut.Mock.VerifyGeneric.Plain(It.IsNot("a"))).Twice(); + await That(sut.Mock.VerifyGeneric.Plain(It.IsNotNull())).Twice(); + } + + [Test] + public async Task WithAMatcherOfABaseTypeOrInterface_ShouldMatchTheTypeArgumentsThatConvertToIt() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + + sut.Plain(new ArgumentException("a")); + sut.Plain(new ArgumentException("b")); + sut.Plain(new ArgumentException("c")); + sut.Plain(1); + sut.Plain("a"); + + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Twice(); + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Twice() + .Because("int and string implement IComparable"); + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Exactly(5); + } + + [Test] + public async Task WithNull_ShouldMatchANullArgumentOfEveryTypeArgument() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + int count = 0; + sut.Mock.SetupGeneric.Plain(null).Do(() => count++); + + sut.Plain(null); + sut.Plain(null); + sut.Plain(null); + sut.Plain("a"); + + await That(count).IsEqualTo(3); + await That(sut.Mock.VerifyGeneric.Plain(null)).Exactly(3); + await That(sut.Mock.VerifyGeneric.Plain(It.IsNull())).Once(); + await That(sut.Mock.VerifyGeneric.Plain(It.IsNull())).Once(); + } + + [Test] + public async Task WithAMatcherOfANullableValueType_ShouldMatchTheTypeArgumentsThatConvertToIt() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + + sut.Plain(1); + sut.Plain(2); + sut.Plain(null); + + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Once() + .Because("int? does not convert to int"); + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Exactly(3) + .Because("int converts to int?"); + } + + [Test] + public async Task WithAMatcherOfAReferenceType_ShouldMatchANullableValueTypeThatIsBoxedToIt() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + + sut.Plain(1); + sut.Plain(2); + + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Twice(); + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Twice(); + } + + [Test] + public async Task WithAParameterOfANullableTypeParameter_ShouldMatchLikeTheTypeParameter() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + List received = []; + sut.Mock.SetupGeneric.Maybe(It.IsAny()).Do(value => received.Add(value)); + + sut.Maybe("a"); + sut.Maybe(null); + sut.Maybe("b"); + sut.Maybe(1); + + await That(received).IsEqualTo(["a", null,]); + await That(sut.Mock.VerifyGeneric.Maybe(It.IsAny())).Twice(); + await That(sut.Mock.VerifyGeneric.Maybe(It.IsAny())).Once(); + } + + [Test] + public async Task WithANullableValueTypeOfATypeParameter_ShouldMatchAMatcherOfTheTypeArgument() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + List received = []; + sut.Mock.SetupGeneric.NullableOnly(It.IsAny()).Do(value => received.Add(value)); + + sut.NullableOnly(1); + sut.NullableOnly(null); + sut.NullableOnly(2); + + await That(received).IsEqualTo([1,]) + .Because("the parameter is an int?, whose values int matches, but a matcher of int does not match null"); + await That(sut.Mock.VerifyGeneric.NullableOnly(It.IsAny())).Twice(); + await That(sut.Mock.VerifyGeneric.NullableOnly(It.IsNull())).Once(); + await That(sut.Mock.VerifyGeneric.NullableOnly(It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.NullableOnly(It.IsAny())).Exactly(3); + } + + [Test] + public async Task WithANullableValueTypeOfATypeParameterAndAnOverload_ShouldMatchAMatcherOfTheNullableType() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + List received = []; + sut.Mock.SetupGeneric.NullableStruct(It.IsAny()).Do(value => received.Add(value)); + + sut.NullableStruct((int?)1); + sut.NullableStruct((int?)null); + sut.NullableStruct((long?)2); + sut.NullableStruct(3); + + await That(received).IsEqualTo([1, null,]) + .Because("a matcher of int binds to the overload with an int parameter"); + await That(sut.Mock.VerifyGeneric.NullableStruct(It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.NullableStruct(It.IsAny())).Once(); + } + + [Test] + public async Task WithAParameterThatPartlyDependsOnATypeArgument_ShouldMatchAMatcherOfADerivedType() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + int count = 0; + sut.Mock.SetupGeneric.Send(It.IsAny()).Do(() => count++); + + _ = sut.Send(new IntRequest()); + _ = sut.Send(new StringRequest()); + _ = sut.Send(new OtherIntRequest()); + + await That(count).IsEqualTo(1) + .Because("IntRequest implements IAnyTypeRequest, and the value of the other call is no IntRequest"); + await That(sut.Mock.VerifyGeneric.Send(It.IsAny>())).Twice(); + await That(sut.Mock.VerifyGeneric.Send(It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.Send(It.IsAny())).Exactly(3); + } + + [Test] + public async Task WithAParameterThatPartlyDependsOnATypeArgument_ShouldAlsoMatchAnotherTypeArgumentThroughVariance() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + int count = 0; + sut.Mock.SetupGeneric.Enumerated(It.IsAny>()).Do(() => count++); + + sut.Enumerated(new List { "a", }); + sut.Enumerated(new List { "b", }); + sut.Enumerated(new[] { "c", }); + + await That(count).IsEqualTo(2) + .Because("List also converts to IEnumerable through variance, and the array is no List"); + await That(sut.Mock.VerifyGeneric.Enumerated(It.IsAny>())).Twice(); + await That(sut.Mock.VerifyGeneric.Enumerated(It.IsAny>())).Exactly(3); + await That(sut.Mock.VerifyGeneric.Enumerated(It.IsAny>())).Exactly(3) + .Because("IEnumerable converts to IEnumerable"); + await That(sut.Mock.VerifyGeneric.Enumerated(It.IsAny())).Once(); + } + + [Test] + public async Task WithAMatcherOfTheNonGenericInterface_ShouldUseTheTypeOfTheMatcher() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + int count = 0; + IParameter matcher = It.IsAny(); + sut.Mock.SetupGeneric.Plain(matcher).Do(() => count++); + + sut.Plain("a"); + sut.Plain("b"); + + await That(count).IsEqualTo(1); + await That(sut.Mock.VerifyGeneric.Plain(matcher)).Once(); + } + + [Test] + public async Task WithSeveralParameters_ShouldMatchTheTypeArgumentOfEachMatcher() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + List received = []; + sut.Mock.SetupGeneric.Pair(It.IsAny(), It.IsAny()).Do((key, value) => received.Add($"{key}={value}")); + + sut.Pair("a", 1); + sut.Pair("b", 2); + sut.Pair("c", "d"); + + await That(received).IsEqualTo(["a=1", "c=d",]); + await That(sut.Mock.VerifyGeneric.Pair(It.IsAny(), It.IsAny())).Twice(); + } + + [Test] + public async Task WithMoreThanFourParameters_ShouldMatchTheTypeArgumentOfTheMatcher() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + int count = 0; + sut.Mock.SetupGeneric.Six(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny()).Do(() => count++); + IVoidMethodSetupWithCallback setup = + sut.Mock.SetupGeneric.Six(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny()); + + sut.Six("a", "b", "c", "d", "e", "f"); + sut.Six("a", "b", "c", "d", "e", "f"); + + await That(count).IsEqualTo(1); + await That(sut.Mock.VerifyGeneric.Six(It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny())).Once(); + await That(sut.Mock.VerifySetup(setup)).Never(); + } + + [Test] + public async Task WithOverloadsOfATypeParameterAndAPartlyDependentType_ShouldApplyTheRuleOfTheCalledOverload_TypeParameterFirst() + { + IAnyTypeCommandSenderTypeParameterFirst sut = IAnyTypeCommandSenderTypeParameterFirst.CreateMock(); + List received = []; + sut.Mock.SetupGeneric.Send(It.IsAny()).Do(() => received.Add("request")); + sut.Mock.SetupGeneric.Send(It.IsAny()).Do(() => received.Add("command")); + + sut.Send(new IntRequest()); + sut.Send(new DerivedCommand()); + sut.Send(new DerivedCommand()); + + await That(received).IsEqualTo(["request", "command",]) + .Because("IntRequest fixes the type argument of IAnyTypeRequest, but a DerivedCommand matcher does not match TRequest = BaseCommand"); + await That(sut.Mock.VerifyGeneric.Send(It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.Send(It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.Send(It.IsAny())).Twice(); + } + + [Test] + public async Task WithOverloadsOfATypeParameterAndAPartlyDependentType_ShouldApplyTheRuleOfTheCalledOverload_RequestFirst() + { + IAnyTypeCommandSenderRequestFirst sut = IAnyTypeCommandSenderRequestFirst.CreateMock(); + List received = []; + IGenericMethodSetup request = sut.Mock.SetupGeneric.Send(It.IsAny()).Do(() => received.Add("request")); + IGenericMethodSetup command = sut.Mock.SetupGeneric.Send(It.IsAny()).Do(() => received.Add("command")); + + sut.Send(new IntRequest()); + sut.Send(new DerivedCommand()); + sut.Send(new DerivedCommand()); + + await That(received).IsEqualTo(["request", "command",]) + .Because("IntRequest fixes the type argument of IAnyTypeRequest, but a DerivedCommand matcher does not match TRequest = BaseCommand"); + await That(sut.Mock.VerifyGeneric.Send(It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.Send(It.IsAny())).Once(); + await That(sut.Mock.VerifySetup(request)).Once(); + await That(sut.Mock.VerifySetup(command)).Once(); + } + + [Test] + public async Task WithOverloadsWhoseParameterDependsOnATypeArgumentInOnlyOne_ShouldOnlyCheckTheValueOfTheOther_TypeParameterFirst() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + int count = 0; + IGenericMethodSetup setup = sut.Mock.SetupGeneric.Overloaded(It.IsAny()).Do(() => count++); + + sut.Overloaded((object)"x"); + sut.Overloaded("y"); + sut.Overloaded("z"); + sut.Overloaded(1); + + await That(count).IsEqualTo(3) + .Because("the parameter of Overloaded(object), which C# also chooses for Overloaded(…), does not depend on the type argument, so only its value is checked"); + await That(sut.Mock.VerifyGeneric.Overloaded(It.IsAny())).Exactly(3); + await That(sut.Mock.VerifySetup(setup)).Exactly(3); + await That(sut.Mock.VerifyGeneric.Overloaded(It.IsAny())).Once(); + } + + [Test] + public async Task WithOverloadsWhoseParameterDependsOnATypeArgumentInOnlyOne_ShouldOnlyCheckTheValueOfTheOther_IndependentFirst() + { + IAnyTypeOverloadedIndependentFirst sut = IAnyTypeOverloadedIndependentFirst.CreateMock(); + int count = 0; + IGenericMethodSetup setup = sut.Mock.SetupGeneric.Overloaded(It.IsAny()).Do(() => count++); + + sut.Overloaded((object)"x"); + sut.Overloaded((object)"y"); + sut.Overloaded("z"); + sut.Overloaded(1); + + await That(count).IsEqualTo(3) + .Because("the parameter of Overloaded(object), which C# also chooses for Overloaded(…), does not depend on the type argument, so only its value is checked"); + await That(sut.Mock.VerifyGeneric.Overloaded(It.IsAny())).Exactly(3); + await That(sut.Mock.VerifySetup(setup)).Exactly(3); + await That(sut.Mock.VerifyGeneric.Overloaded(It.IsAny())).Once(); + } + + [Test] + public async Task WithOverloadsWhoseParameterDependsOnATypeArgumentInOnlyOne_WhenTheOtherIsCalledWithObject_ShouldAgreeWithTheRecordedCall_TypeParameterFirst() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + int count = 0; + IGenericMethodSetup setup = sut.Mock.SetupGeneric.Overloaded(It.IsAny()).Do(() => count++); + + CallOverloaded(sut, (object)"x"); + CallOverloaded(sut, (object)1); + + await That(count).IsEqualTo(1) + .Because("the recorded call looks like one of Overloaded(object), whose value is checked"); + await That(sut.Mock.VerifyGeneric.Overloaded(It.IsAny())).Once(); + await That(sut.Mock.VerifySetup(setup)).Once(); + + static void CallOverloaded(IGenericMethodAnyTypeArgument mock, TValue value) + => mock.Overloaded(value); + } + + [Test] + public async Task WithOverloadsWhoseParameterDependsOnATypeArgumentInOnlyOne_WhenTheOtherIsCalledWithObject_ShouldAgreeWithTheRecordedCall_IndependentFirst() + { + IAnyTypeOverloadedIndependentFirst sut = IAnyTypeOverloadedIndependentFirst.CreateMock(); + int count = 0; + IGenericMethodSetup setup = sut.Mock.SetupGeneric.Overloaded(It.IsAny()).Do(() => count++); + + CallOverloaded(sut, (object)"x"); + CallOverloaded(sut, (object)1); + + await That(count).IsEqualTo(1) + .Because("the recorded call looks like one of Overloaded(object), whose value is checked"); + await That(sut.Mock.VerifyGeneric.Overloaded(It.IsAny())).Once(); + await That(sut.Mock.VerifySetup(setup)).Once(); + + static void CallOverloaded(IAnyTypeOverloadedIndependentFirst mock, TValue value) + => mock.Overloaded(value); + } + + [Test] + public async Task WithOverloadsRecognizedByADifferentNumberOfParameters_ShouldApplyTheRuleOfTheCalledOverload_EnumerableFirst() + { + IAnyTypeAddEnumerableFirst sut = IAnyTypeAddEnumerableFirst.CreateMock(); + List received = []; + IGenericMethodSetup strings = sut.Mock.SetupGeneric.Add(It.IsAny(), It.IsAny()) + .Do(() => received.Add("string")); + IGenericMethodSetup ints = sut.Mock.SetupGeneric.Add(It.IsAny(), It.IsAny()) + .Do(() => received.Add("int")); + IGenericMethodSetup lists = sut.Mock.SetupGeneric.Add(It.IsAny(), It.IsAny>()) + .Do(() => received.Add("list")); + + sut.Add("k", "x"); + sut.Add("k", 5); + sut.Add("k", new List { 1, }); + sut.Add("k", new List { 2, }); + sut.Add("k", "y"); + + await That(received).IsEqualTo(["list", "list", "string",]) + .Because("the value parameter is a type parameter in Add(string, T), so neither IComparable nor int? match, but only partly depends on it in Add(string, IEnumerable)"); + await That(sut.Mock.VerifySetup(strings)).Once(); + await That(sut.Mock.VerifySetup(ints)).Never(); + await That(sut.Mock.VerifySetup(lists)).Twice(); + await That(sut.Mock.VerifyGeneric.Add(It.IsAny(), It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.Add(It.IsAny(), It.IsAny())).Never(); + } + + [Test] + public async Task WithOverloadsRecognizedByADifferentNumberOfParameters_ShouldApplyTheRuleOfTheCalledOverload_TypeParameterFirst() + { + IAnyTypeAddTypeParameterFirst sut = IAnyTypeAddTypeParameterFirst.CreateMock(); + List received = []; + IGenericMethodSetup strings = sut.Mock.SetupGeneric.Add(It.IsAny(), It.IsAny()) + .Do(() => received.Add("string")); + IGenericMethodSetup ints = sut.Mock.SetupGeneric.Add(It.IsAny(), It.IsAny()) + .Do(() => received.Add("int")); + IGenericMethodSetup lists = sut.Mock.SetupGeneric.Add(It.IsAny(), It.IsAny>()) + .Do(() => received.Add("list")); + + sut.Add("k", "x"); + sut.Add("k", 5); + sut.Add("k", new List { 1, }); + sut.Add("k", new List { 2, }); + sut.Add("k", "y"); + + await That(received).IsEqualTo(["list", "list", "string",]) + .Because("the value parameter is a type parameter in Add(string, T), so neither IComparable nor int? match, but only partly depends on it in Add(string, IEnumerable)"); + await That(sut.Mock.VerifySetup(strings)).Once(); + await That(sut.Mock.VerifySetup(ints)).Never(); + await That(sut.Mock.VerifySetup(lists)).Twice(); + await That(sut.Mock.VerifyGeneric.Add(It.IsAny(), It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.Add(It.IsAny(), It.IsAny())).Never(); + } + + [Test] + public async Task WithAMatcherOfSeveralCollectionTypes_ShouldMatchEveryTypeArgument() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + int count = 0; + sut.Mock.SetupGeneric.Plain(It.Contains(1)).Do(() => count++); + + sut.Plain(new List { 1, }); + sut.Plain(new[] { 1, }); + sut.Plain>(new[] { 2, }); + + await That(count).IsEqualTo(2) + .Because("It.Contains implements IParameter for several collection types, so it checks the value for any type argument"); + } + + private class BaseCommand : IAnyTypeCommand, IAnyTypeRequest; + + private sealed class DerivedCommand : BaseCommand; + + private sealed class OtherIntRequest : IAnyTypeRequest; + } +} diff --git a/Tests/Mockolate.Tests/GeneratorShapes/GenericMethodAnyTypeArgumentTests.cs b/Tests/Mockolate.Tests/GeneratorShapes/GenericMethodAnyTypeArgumentTests.cs index b870fb351..659e3db5c 100644 --- a/Tests/Mockolate.Tests/GeneratorShapes/GenericMethodAnyTypeArgumentTests.cs +++ b/Tests/Mockolate.Tests/GeneratorShapes/GenericMethodAnyTypeArgumentTests.cs @@ -10,7 +10,7 @@ namespace Mockolate.Tests.GeneratorShapes; public sealed partial class GenericMethodAnyTypeArgumentTests { [Test] - public async Task SetupGeneric_ShouldMatchEveryTypeArgument() + public async Task SetupGeneric_ShouldMatchTheTypeArgumentOfTheMatcher() { IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); List received = []; @@ -20,8 +20,24 @@ public async Task SetupGeneric_ShouldMatchEveryTypeArgument() sut.Plain("b"); sut.Plain(1); - await That(received).IsEqualTo(["a", "b",]) - .Because("the matcher is checked against the runtime value, whatever the type argument"); + await That(received).IsEqualTo(["a",]) + .Because("a matcher of string matches the calls with the type argument string, not those with object"); + } + + [Test] + public async Task SetupGeneric_WithAnObjectMatcher_ShouldMatchEveryTypeArgument() + { + IGenericMethodAnyTypeArgument sut = IGenericMethodAnyTypeArgument.CreateMock(); + List received = []; + sut.Mock.SetupGeneric.Plain(It.IsAny()).Do(value => received.Add(value)); + + sut.Plain("a"); + sut.Plain("b"); + sut.Plain(1); + sut.Plain(null); + + await That(received).IsEqualTo(["a", "b", 1, null,]); + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Exactly(4); } [Test] @@ -51,12 +67,13 @@ public async Task SetupGeneric_ShouldMatchValueTypesWithATypedMatcher() sut.Plain("a"); sut.Plain(3); - await That(received).IsEqualTo([1, 3,]) - .Because("the matcher is checked against the boxed value, whatever the type argument"); - await That(matched).IsEqualTo([1, 3,]); - await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Twice(); + await That(received).IsEqualTo([1,]) + .Because("a matcher of int matches the calls with the type argument int, not those with object"); + await That(matched).IsEqualTo([1,]); + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Once(); await That(sut.Mock.VerifyGeneric.Plain(It.Is(1))).Once(); await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.Plain(It.Is(3))).Once(); } [Test] @@ -362,7 +379,8 @@ public async Task VerifyGeneric_ShouldCountEveryTypeArgument() _ = sut.Send(new IntRequest()); _ = sut.Send(new StringRequest()); - await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Twice(); + await That(sut.Mock.VerifyGeneric.Plain(It.IsAny())).Once(); + await That(sut.Mock.VerifyGeneric.Plain(It.Satisfies(value => value is string))).Twice(); await That(sut.Mock.VerifyGeneric.Plain(It.Satisfies(value => value is int))).Once(); await That(sut.Mock.VerifyGeneric.Plain(Match.AnyParameters())).Exactly(3); await That(sut.Mock.VerifyGeneric.Deserialize(It.Is("x"))).Once(); @@ -437,7 +455,7 @@ public async Task VerifySetup_ShouldCountCallsOfEveryTypeArgument() sut.Plain(1); sut.Sibling(1); - await That(sut.Mock.VerifySetup(plain)).Twice(); + await That(sut.Mock.VerifySetup(plain)).Once(); await That(sut.Mock.VerifySetup(any)).Exactly(3) .Because("the non-generic sibling is another method"); } @@ -523,7 +541,10 @@ public async Task WithFourParameters_ShouldMatchEveryTypeArgument() sut.Four("a", 1, 2, "d"); sut.Four(1, 2, 3, 4); - await That(count).IsEqualTo(2); + await That(count).IsEqualTo(1) + .Because("each matcher of string only matches the calls with the type argument string"); + await That(sut.Mock.VerifyGeneric.Four(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Exactly(3); await That(sut.Mock.VerifyGeneric.Four(Match.AnyParameters())).Exactly(3); } diff --git a/Tests/Mockolate.Tests/Logging/LoggerTests.BeginScopeTests.cs b/Tests/Mockolate.Tests/Logging/LoggerTests.BeginScopeTests.cs index b9f5e85a6..e8927fed5 100644 --- a/Tests/Mockolate.Tests/Logging/LoggerTests.BeginScopeTests.cs +++ b/Tests/Mockolate.Tests/Logging/LoggerTests.BeginScopeTests.cs @@ -125,6 +125,22 @@ public async Task SetupGeneric_ShouldStillMatchTheScopesOfAnyStateType() await That(states).IsEqualTo(["scope", 42,]); } + [Test] + public async Task SetupGeneric_WithATypedMatcher_ShouldOnlyMatchTheScopesOfThatStateType() + { + List states = []; + ILogger logger = ILogger.CreateMock(); + logger.Mock.SetupGeneric.BeginScope(It.IsAny()).Do(state => states.Add(state)); + + logger.BeginScope("scope")?.Dispose(); + logger.BeginScope("object")?.Dispose(); + logger.BeginScope(42)?.Dispose(); + + await That(states).IsEqualTo(["scope",]); + await That(logger.Mock.VerifyGeneric.BeginScope(It.IsAny())).Once(); + await That(logger.Mock.VerifyGeneric.BeginScope(It.IsAny())).Exactly(3); + } + [Test] public async Task Verify_WithMessageTemplate_ShouldMatchTheTemplateAndProperties() {