Skip to content

Commit 1c6a1fa

Browse files
authored
Merge pull request #396 from stakx/setup-null-return
Allow setting up null return values using `Mock.Of`
2 parents b23886d + c7fad7f commit 1c6a1fa

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

Source/Linq/MockSetupsBuilder.cs

+5
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,11 @@ private static Expression ConvertToSetup(Expression targetObject, Expression lef
226226
.MakeGenericType(sourceType, returnType)
227227
.GetMethod("Returns", new[] { returnType });
228228

229+
if (right is ConstantExpression constExpr && constExpr.Value == null)
230+
{
231+
right = Expression.Constant(null, left.Type);
232+
}
233+
229234
return Expression.NotEqual(
230235
Expression.Call(FluentMockVisitor.Accept(left), returnsMethod, right),
231236
Expression.Constant(null));

UnitTests/Regressions/IssueReportsFixture.cs

+27
Original file line numberDiff line numberDiff line change
@@ -1130,6 +1130,33 @@ public class Foo : IFoo
11301130

11311131
#endregion
11321132

1133+
#region 337
1134+
1135+
public class Issue337
1136+
{
1137+
[Fact]
1138+
public void Mock_Of_can_setup_null_return_value()
1139+
{
1140+
// The following mock setup might appear redundant; after all, `null` is
1141+
// the default value returned for most reference types. However, this test
1142+
// becomes relevant once Moq starts supporting custom implementations of
1143+
// `IDefaultValueProvider`. Then it might no longer be a given that `null`
1144+
// is the default return value that noone would want to explicitly set up.
1145+
var userProvider = Mock.Of<IUserProvider>(p => p.GetUserByEmail("[email protected]") == null);
1146+
var user = userProvider.GetUserByEmail("[email protected]");
1147+
Assert.Null(user);
1148+
}
1149+
1150+
public class User { }
1151+
1152+
public interface IUserProvider
1153+
{
1154+
User GetUserByEmail(string email);
1155+
}
1156+
}
1157+
1158+
#endregion
1159+
11331160
#region 340
11341161

11351162
#if FEATURE_SERIALIZATION

0 commit comments

Comments
 (0)