Skip to content

Commit f315474

Browse files
committed
add tests for ParameterIncompatibleWithMatchedType
1 parent 24b8d8a commit f315474

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/Moq/MatcherFactory.cs

+6-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ public static Pair<IMatcher, Expression> CreateMatcher(Expression argument, Para
110110
matchedValuesType = convertExpression.Operand.Type;
111111
}
112112

113-
if (!parameter.ParameterType.IsAssignableFrom(matchedValuesType))
113+
if (ParameterIncompatibleWithMatchedType(parameterType: parameter.ParameterType, matchedValuesType))
114114
{
115115
throw new ArgumentException(
116116
string.Format(
@@ -126,6 +126,11 @@ public static Pair<IMatcher, Expression> CreateMatcher(Expression argument, Para
126126
return MatcherFactory.CreateMatcher(argument);
127127
}
128128

129+
public static bool ParameterIncompatibleWithMatchedType(Type parameterType, Type matchType)
130+
{
131+
return !parameterType.IsAssignableFrom(matchType);
132+
}
133+
129134
public static Pair<IMatcher, Expression> CreateMatcher(Expression expression)
130135
{
131136
// Type inference on the call might

tests/Moq.Tests/Matchers/AnyMatcherFixture.cs

+26
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,32 @@ public void DoesntMatchIfNotAssignableType()
5050
Assert.False(matcher.Matches("foo", typeof(IFormatProvider)));
5151
}
5252

53+
[Fact]
54+
public void ParameterIncompatibleWithMatchedType()
55+
{
56+
//shorthand wrapper
57+
void AssertNotCompatible(Type parameterType, Type matchType)
58+
{
59+
Assert.True(MatcherFactory.ParameterIncompatibleWithMatchedType(parameterType: parameterType, matchType: matchType));
60+
}
61+
//shorthand wrapper
62+
void AssertCompatible(Type parameterType, Type matchType)
63+
{
64+
Assert.False(MatcherFactory.ParameterIncompatibleWithMatchedType(parameterType: parameterType, matchType: matchType));
65+
}
66+
67+
// incompatible tests
68+
AssertNotCompatible(parameterType: typeof(DateTimeOffset), matchType: typeof(DateTime));
69+
AssertNotCompatible(parameterType: typeof(DateTime), matchType: typeof(DateTimeOffset));
70+
AssertNotCompatible(parameterType: typeof(DateTime), matchType: typeof(object));
71+
72+
// if mocked method parameter type is an object, should allow `It.IsAny<string>()`
73+
AssertCompatible(parameterType: typeof(object), matchType: typeof(string));
74+
75+
// if mocked method parameter type is an object, should allow `It.IsAny<DateTime>()`
76+
AssertCompatible(parameterType: typeof(object), matchType: typeof(DateTime));
77+
}
78+
5379
private LambdaExpression ToExpression<TResult>(Expression<Func<TResult>> expr)
5480
{
5581
return expr;

0 commit comments

Comments
 (0)