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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions Docs/pages/06-parameter-matching.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<int>(), 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<int>(), 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<object>()` or `It.Satisfies<object>(...)`, matches every type argument:

```csharp
public interface IChocolateSerializer
Expand All @@ -189,14 +191,28 @@ serializer.Mock.SetupGeneric.Deserialize(It.Is("{")).Throws<FormatException>();

void Act() => serializer.Deserialize<DarkChocolate>("{");
serializer.Write("dark");
serializer.Write<object>("milk");
serializer.Write(42);

await That(Act).Throws<FormatException>();
await That(serializer.Mock.VerifyGeneric.Write(It.IsAny<string>())).Once();
await That(serializer.Mock.VerifyGeneric.Write(It.IsAny<int>())).Once();
await That(serializer.Mock.VerifyGeneric.Write(Match.AnyParameters())).Twice();
await That(serializer.Mock.VerifyGeneric.Write(It.Satisfies<object>(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<string>()` matches `Write<string>(...)`, but neither `Write<object>("milk")` nor `Write<int>(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<Exception>()` matches `Write<ArgumentException>(...)` as well.
- Nullable value types convert as in C#: `It.IsAny<int?>()` matches `Write<int>(...)`, but `It.IsAny<int>()` does not match `Write<int?>(...)`. `It.IsAny<IComparable>()` matches both, as an `int?` is boxed to an `int`.
- `null` matches a `null` argument of every type argument, `It.IsNull<string>()` only one of the type argument `string`.
- When the type of the parameter only partly depends on a type parameter, such as `IRequest<T>`, `IEnumerable<T>` 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<TResponse>(IRequest<TResponse> request)`, `It.IsAny<Ping>()` with `Ping : IRequest<int>` matches the calls of `Send<int>` with a `Ping`; for `Store<T>(IEnumerable<T> items)`, `It.IsAny<List<string>>()` matches the calls of `Store<string>` with a `List<string>`, and, as `IEnumerable<out T>` is covariant, also those of `Store<object>`; for `Store<T>(T? item) where T : struct`, `It.IsAny<int>()` matches the calls of `Store<int>` that pass a value.
- A matcher that implements `IParameter<T>` 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<T>(object value)` next to `Overloaded<T>(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<object>(...)` of `Overloaded<T>(T value)` from generic code, which is recorded like a call of `Overloaded<T>(object value)`; with several such parameters, as in `P<T>(T a, object b)` next to `P<T>(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<IEvent>(orderPlaced)`, is not matched by `It.IsAny<OrderPlaced>()`. Check the value instead: `SetupGeneric.Publish(It.Satisfies<object>(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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -973,7 +973,7 @@ bool IsMatchingSetup(global::Mockolate.Setup.MethodSetup candidate)
{
ScopeSetup scopeCandidate => scopeCandidate.MatchesScope(invocation),
global::Mockolate.Setup.ReturnMethodSetup<global::System.IDisposable?, TState> typedSetup => typedSetup.Name == name && typedSetup.Matches(state),
global::Mockolate.Setup.VoidMethodSetup<object?> anyTypeCandidate => anyTypeCandidate.Name == anyTypeName && anyTypeCandidate.Matches(state),
global::Mockolate.Setup.VoidMethodSetup<object?> anyTypeCandidate => anyTypeCandidate.Name == anyTypeName && global::Mockolate.Internals.GenericMethodInvocations.MatchesParameterType(anyTypeCandidate, 0, typeof(TState), global::Mockolate.Internals.ParameterTypeDependency.TypeParameter) && anyTypeCandidate.Matches(state),
_ => false,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -917,18 +917,24 @@ private static void AppendGenericMethodSetups(StringBuilder sb, int numberOfPara
$"{isCallOf}, global::Mockolate.Parameters.IParameters parameters{parameterNames}", $", parameters{parameterNameArgs}");
AppendAnyTypeArgumentsSetup("GenericMethodSetup", "WithParameterCollection",
"matching against individual <see cref=\"global::Mockolate.Parameters.IParameterMatch{T}\" />",
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/// <summary>Setup for a generic method with ").Append(numberOfParameters)
.Append(" parameters, for any type argument, ").Append(matching).Append(".</summary>").AppendLine();
sb.Append("\t[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]").AppendLine();
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();
Expand All @@ -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/// <inheritdoc cref=\"global::Mockolate.Internals.IGenericMethodParameterTypes.MatchesParameterType(int, global::System.Type, global::Mockolate.Internals.ParameterTypeDependency)\" />").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();
Expand Down
Loading
Loading