Skip to content

Commit

Permalink
Stop searching for setup when first match found (#1004)
Browse files Browse the repository at this point in the history
* Why not just pick the first setup that matches?

Searching for a more perfect match after a matching setup has been
identified appears to go against the principle of more recent setups
overriding earlier ones, anyway.

* ... and sure enough this breaks a faulty test!

The test changed here shouldn't have passed in the first place, since
the setup for `Method<object>` essentially shadowed the earlier ones
for `Method<bool>` and `Method<int>`.
  • Loading branch information
stakx authored Apr 21, 2020
1 parent 8cca0e8 commit 4586f77
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 17 deletions.
19 changes: 3 additions & 16 deletions src/Moq/SetupCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,6 @@ public Setup FindMatchFor(Invocation invocation)
return null;
}

Setup matchingSetup = null;

lock (this.setups)
{
// Iterating in reverse order because newer setups are more relevant than (i.e. override) older ones
Expand All @@ -138,25 +136,14 @@ public Setup FindMatchFor(Invocation invocation)
var setup = this.setups[i];
if (setup.IsOverridden) continue;

// the following conditions are repetitive, but were written that way to avoid
// unnecessary expensive calls to `setup.Matches`; cheap tests are run first.
if (matchingSetup == null && setup.Matches(invocation))
{
matchingSetup = setup;
if (setup.Method == invocation.Method)
{
break;
}
}
else if (setup.Method == invocation.Method && setup.Matches(invocation))
if (setup.Matches(invocation))
{
matchingSetup = setup;
break;
return setup;
}
}
}

return matchingSetup;
return null;
}

public IEnumerable<Setup> GetInnerMockSetups()
Expand Down
2 changes: 1 addition & 1 deletion tests/Moq.Tests/ItIsAnyTypeFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ public class ItIsAnyTypeFixture
public void Setup_without_It_IsAnyType()
{
var mock = new Mock<IX>();
mock.Setup(x => x.Method<object>());
mock.Setup(x => x.Method<bool>());
mock.Setup(x => x.Method<int>());
mock.Setup(x => x.Method<object>());
mock.Setup(x => x.Method<string>());

mock.Object.Method<bool>();
Expand Down

0 comments on commit 4586f77

Please sign in to comment.