Skip to content

Commit

Permalink
FluentMockContext: Fix default value provider bug (#542)
Browse files Browse the repository at this point in the history
* Add failing test
* Restore provider correctly in `FluentMockContext`
  • Loading branch information
stakx committed Dec 3, 2017
1 parent e9e153c commit 0bd3746
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
16 changes: 16 additions & 0 deletions Moq.Tests/CustomDefaultValueProviderFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,24 @@ public void Inner_mocks_inherit_custom_default_value_provider_from_outer_mock()
Assert.Equal(expectedReturnValue, actualReturnValue);
}

[Fact]
public void FluentMockContext_properly_restores_custom_default_value_provider()
{
var customDefaultValueProvider = new ConstantDefaultValueProvider(42);
var mock = new Mock<IFoo>() { DefaultValueProvider = customDefaultValueProvider };

mock.VerifySet(m => m.Inner.Value = 1, Times.Never);
// ^^^^^^^^^^^^^^^^^^^^^^
// Moq has to execute this action to analyse what is being set. Because this is a multi-dot expression,
// it temporarily switches to DefaultValue.Mock. Once it's done, it should switch back to the one we
// set up above.

Assert.Same(customDefaultValueProvider, mock.DefaultValueProvider);
}

public interface IFoo
{
int Value { get; set; }
int GetValue();
int[] GetValues();
IFoo Inner { get; }
Expand Down
7 changes: 4 additions & 3 deletions Source/FluentMockContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,15 @@ public void Dispose()

internal class MockInvocation : IDisposable
{
private DefaultValue defaultValue;
private DefaultValueProvider defaultValueProvider;

public MockInvocation(Mock mock, Invocation invocation, Match matcher)
{
this.Mock = mock;
this.Invocation = invocation;
this.Match = matcher;
defaultValue = mock.DefaultValue;
this.defaultValueProvider = mock.DefaultValueProvider;

// Temporarily set mock default value to Mock so that recursion works.
mock.DefaultValue = DefaultValue.Mock;
}
Expand All @@ -120,7 +121,7 @@ public MockInvocation(Mock mock, Invocation invocation, Match matcher)

public void Dispose()
{
Mock.DefaultValue = defaultValue;
this.Mock.DefaultValueProvider = this.defaultValueProvider;
}
}
}
Expand Down

0 comments on commit 0bd3746

Please sign in to comment.