Skip to content

Commit

Permalink
Merge pull request #1085 from stakx/linq
Browse files Browse the repository at this point in the history
Enable parameterized `Mock.Of<>` in query comprehension `from` clause
  • Loading branch information
stakx committed Oct 28, 2020
2 parents 3f7dff8 + e49c708 commit 7b8b7e4
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ The format is loosely based on [Keep a Changelog](http://keepachangelog.com/en/1

* `SetupProperty` fails if property getter and setter are not both defined in mocked type (@stakx, #1017)
* Expression tree argument not matched when it contains a captured variable &ndash; evaluate all captures to their current values when comparing two expression trees (@QTom01, #1054)
* Failure when parameterized `Mock.Of<>` is used in query comprehension `from` clause (@stakx, #982)


## 4.14.7 (2020-10-14)
Expand Down
9 changes: 9 additions & 0 deletions src/Moq/Linq/MockSetupsBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ internal class MockSetupsBuilder : ExpressionVisitor
private static readonly string[] unsupportedMethods = new[] { "All", "Any", "Last", "LastOrDefault", "Single", "SingleOrDefault" };

private int stackIndex;
private int quoteDepth;

public MockSetupsBuilder()
{
Expand Down Expand Up @@ -91,6 +92,14 @@ protected override Expression VisitUnary(UnaryExpression node)
return ConvertToSetup(node.Operand, Expression.Constant(false)) ?? base.VisitUnary(node);
}

if (node.NodeType == ExpressionType.Quote)
{
this.quoteDepth++;
var result = this.quoteDepth > 1 ? node : base.VisitUnary(node);
this.quoteDepth--;
return result;
}

return base.VisitUnary(node);
}

Expand Down
23 changes: 22 additions & 1 deletion tests/Moq.Tests/Linq/QueryableMocksFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

using Xunit;

namespace Moq.Tests
namespace Moq.Tests.Linq
{
public class QueryableMocksFixture
{
Expand Down Expand Up @@ -212,6 +212,27 @@ public void Strict_Mocks_Of_with_specification_expression_will_throw_for_non_set
Assert.Throws<MockException>(() => _ = foo.Name);
}

[Fact]
public void Multiple_mocks_with_query_comprehension_syntax__predicates_in_where_clause()
{
var x = (from x1 in Mocks.Of<IFoo>()
from __ in Mocks.Of<IFoo>()
where x1.Name == "1" && __.Name == "2"
select x1)
.First();
Assert.Equal("1", x.Name);
}

[Fact]
public void Multiple_mocks_with_query_comprehension_syntax__predicates_in_from_clause()
{
var x = (from x1 in Mocks.Of<IFoo>(_ => _.Name == "1")
from __ in Mocks.Of<IFoo>(_ => _.Name == "2")
select x1)
.First();
Assert.Equal("1", x.Name);
}

public class Dto
{
public string Value { get; set; }
Expand Down

0 comments on commit 7b8b7e4

Please sign in to comment.