Skip to content

Allow setting up null return values using Mock.Of #396

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

Merged
merged 2 commits into from
Jun 27, 2017
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Source/Linq/MockSetupsBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,11 @@ private static Expression ConvertToSetup(Expression targetObject, Expression lef
.MakeGenericType(sourceType, returnType)
.GetMethod("Returns", new[] { returnType });

if (right is ConstantExpression constExpr && constExpr.Value == null)
{
right = Expression.Constant(null, left.Type);
}

return Expression.NotEqual(
Expression.Call(FluentMockVisitor.Accept(left), returnsMethod, right),
Expression.Constant(null));
Expand Down
27 changes: 27 additions & 0 deletions UnitTests/Regressions/IssueReportsFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,33 @@ public class Foo : IFoo

#endregion

#region 337

public class Issue337
{
[Fact]
public void Mock_Of_can_setup_null_return_value()
{
// The following mock setup might appear redundant; after all, `null` is
// the default value returned for most reference types. However, this test
// becomes relevant once Moq starts supporting custom implementations of
// `IDefaultValueProvider`. Then it might no longer be a given that `null`
// is the default return value that noone would want to explicitly set up.
var userProvider = Mock.Of<IUserProvider>(p => p.GetUserByEmail("[email protected]") == null);
var user = userProvider.GetUserByEmail("[email protected]");
Assert.Null(user);
}

public class User { }

public interface IUserProvider
{
User GetUserByEmail(string email);
}
}

#endregion

#region 340

#if FEATURE_SERIALIZATION
Expand Down