Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make guard against unmatchable matchers less strict to enable user-based wildcard matching #1202

Merged
merged 5 commits into from
Aug 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ and `Setup(x => x.GetFooAsync(It.IsAny<string>()).Result).Throws((string s) => n

#### Fixed

* The guard against unmatchable matchers (added in #900) was too strict; relaxed it to enable an alternative user-code shorthand `_` for `It.IsAny<>()` (@adamfk, #1199)
* mock.Protected() setup methods fail when argument is of type Expression (@tonyhallett, #1189)
* Parameter is invalid in Protected().SetupSet() ... VerifySet (@tonyhallett, #1186)

Expand Down
30 changes: 23 additions & 7 deletions src/Moq/MatcherFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,30 @@ internal static class MatcherFactory
var convertExpression = (UnaryExpression)argument;
if (convertExpression.Method?.Name == "op_Implicit")
{
if (!parameter.ParameterType.IsAssignableFrom(convertExpression.Operand.Type) && convertExpression.Operand.IsMatch(out _))
if (convertExpression.Operand.IsMatch(out var match))
{
throw new ArgumentException(
string.Format(
Resources.ArgumentMatcherWillNeverMatch,
convertExpression.Operand.ToStringFixed(),
convertExpression.Operand.Type.GetFormattedName(),
parameter.ParameterType.GetFormattedName()));
Type matchedValuesType;

if (match.GetType().IsGenericType)
{
// If match type is `Match<int>`, matchedValuesType set to `int`
// Fix for https://github.com/moq/moq4/issues/1199
adamfk marked this conversation as resolved.
Show resolved Hide resolved
matchedValuesType = match.GetType().GenericTypeArguments[0];
}
else
{
matchedValuesType = convertExpression.Operand.Type;
}

if (!matchedValuesType.IsAssignableFrom(parameter.ParameterType))
{
throw new ArgumentException(
string.Format(
Resources.ArgumentMatcherWillNeverMatch,
convertExpression.Operand.ToStringFixed(),
convertExpression.Operand.Type.GetFormattedName(),
parameter.ParameterType.GetFormattedName()));
}
}
}
}
Expand Down
202 changes: 202 additions & 0 deletions tests/Moq.Tests/Matchers/Wildcard.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
using Xunit;
using System;

/// <summary>
/// Tests for https://github.com/moq/moq4/issues/1199
/// </summary>

namespace Moq.Tests.Matchers.Wildcard
{
using static AutoIsAny; // note using static to simplify syntax

/// <summary>
/// Helper class provided by user
/// </summary>
public abstract class AutoIsAny
{
public static AnyValue _
{
get
{
It.IsAny<object>();
return new AnyValue();
}
}
}

/// <summary>
/// Helper class provided by user. Interfaces implemented via IDE auto explicit interface implementation
/// or Roslyn analyzer/code fix.
/// </summary>
public class AnyValue : ISomeService
{
int ISomeService.Calc(int a, int b, int c, int d)
{
throw new NotImplementedException();
}

int ISomeService.DoSomething(ISomeService a, GearId b, int c)
{
throw new NotImplementedException();
}

int ISomeService.Echo(int a)
{
throw new NotImplementedException();
}

int ISomeService.UseAnimal(Animal a)
{
throw new NotImplementedException();
}

int ISomeService.UseDolphin(Dolphin a)
{
throw new NotImplementedException();
}

int ISomeService.UseInterface(ISomeService a)
{
throw new NotImplementedException();
}

public static implicit operator int(AnyValue _) => default;
public static implicit operator byte(AnyValue _) => default;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@stakx should I switch these back to using It.IsAny<T>()? Or should I rely on implicit conversion functions like this never being called? Just thinking about making a source generator for people to use and if possible, I don't want to rely on behavior that may be changed.

Copy link
Contributor

@stakx stakx Aug 23, 2021

Choose a reason for hiding this comment

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

No, keep these as default. You should only have one call to a matcher per parameter. If you have more than that, you may confuse the SetupSet / VerifySet delegate reconstruction machinery (ActionObserver), which attempts to distribute recorded matchers over the available parameters.

Note also this comment in ActionObserver, which states Moq's general assumption of matchers returning default(T):

https://github.com/moq/moq4/blob/abc05532d7350c5431a5d89a91b667d569fa4d65/src/Moq/ActionObserver.cs#L127-L128

Meaning, if you want SetupSet and VerifySet to interact correctly with your _ shorthand, it should probably return default / null instead of new AnyValue().

public static implicit operator GearId(AnyValue _) => default;
public static implicit operator Animal(AnyValue _) => default;
public static implicit operator Dolphin(AnyValue _) => default;
}


public class Tests
{
Mock<ISomeService> mock;
ISomeService obj;

public Tests()
{
mock = new Mock<ISomeService>();
obj = mock.Object;
}

[Fact]
public void Echo_1Primitive()
{
mock.Setup(obj => obj.Echo(_)).Returns(777);
Assert.Equal(777, obj.Echo(1));
}

[Fact]
public void Calc_4Primitives()
{
mock.Setup(obj => obj.Calc(_, _, _, _)).Returns(999);
Assert.Equal(999, obj.Calc(1, 2, 3, 4));
}

[Fact]
public void UseInterface()
{
mock.Setup(obj => obj.UseInterface(_)).Returns(555);
Assert.Equal(555, obj.UseInterface(null));

var realService = new SomeService();
Assert.Equal(555, obj.UseInterface(realService));
}

[Fact]
public void DoSomething_MixedTypes()
{
mock.Setup(obj => obj.DoSomething(_, _, _)).Returns(444);
Assert.Equal(444, obj.DoSomething(null, GearId.Neutral, 1));
}

[Fact]
public void UseAnimal()
{
mock.Setup(obj => obj.UseAnimal(_)).Returns(777);
Assert.Equal(777, obj.UseAnimal(new Animal()));
Assert.Equal(777, obj.UseAnimal(new Dolphin()));
}

[Fact]
public void UseDolphin()
{
mock.Setup(obj => obj.UseDolphin(_)).Returns(888);
Assert.Equal(888, obj.UseDolphin(new Dolphin()));
}
}


/// <summary>
/// Example enum
/// </summary>
public enum GearId
{
Reverse,
Neutral,
Gear1,
}


/// <summary>
/// Example interface
/// </summary>
public interface ISomeService
{
int Echo(int a);
int Calc(int a, int b, int c, int d);
int UseInterface(ISomeService a);
int DoSomething(ISomeService a, GearId b, int c);
int UseAnimal(Animal a);
int UseDolphin(Dolphin a);
}


/// <summary>
/// just a class that implements interface
/// </summary>
public class SomeService : ISomeService
{
public int Calc(int a, int b, int c, int d)
{
throw new NotImplementedException();
}

public int DoSomething(ISomeService a, GearId b, int c)
{
throw new NotImplementedException();
}

public int Echo(int a)
{
throw new NotImplementedException();
}

public int UseAnimal(Animal a)
{
throw new NotImplementedException();
}

public int UseDolphin(Dolphin a)
{
throw new NotImplementedException();
}

public int UseInterface(ISomeService a)
{
throw new NotImplementedException();
}
}


public class Animal
{

}


public class Dolphin : Animal
{

}
}