Skip to content
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

Fix SetupAllProperties to override pre-existing property setups (#837) #840

Merged
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
4 changes: 4 additions & 0 deletions src/Moq/Mock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,10 @@ internal static void SetupAllProperties(Mock mock)

internal static void SetupAllProperties(Mock mock, DefaultValueProvider defaultValueProvider)
{
mock.Setups.RemoveAll(x => x.Method.IsPropertyAccessor());
// Removing all the previous properties setups to keep the behaviour of overriding
// existing setups in `SetupAllProperties`.

mock.AutoSetupPropertiesDefaultValueProvider = defaultValueProvider;
// `SetupAllProperties` no longer performs properties setup like in previous versions.
// Instead it just enables a switch to setup properties on-demand at the moment of first access.
Expand Down
15 changes: 15 additions & 0 deletions src/Moq/SetupCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ public bool Any(Func<Setup, bool> predicate)
}
}

public void RemoveAll(Func<Setup, bool> predicate)
{
// Fast path (no `lock`) when there are no setups:
if (this.setups.Count == 0)
{
return;
}

lock (this.setups)
{
this.setups.RemoveAll(x => predicate(x));
this.overridden = 0U;
}
}

public void Clear()
{
lock (this.setups)
Expand Down
26 changes: 26 additions & 0 deletions tests/Moq.Tests/StubExtensionsFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,32 @@ public void SetupAllProperties_should_setup_properties_from_interface_with_write
Assert.Equal("test", asReimplementedInterface.WriteAccessInDerived);
}

[Fact]
public void SetupAllProperties_should_override_previous_SetupAllProperties()
{
var mock = new Mock<IBar>();

mock.SetReturnsDefault(1);
mock.SetupAllProperties();
Assert.Equal(1, mock.Object.Value);

mock.Object.Value = 2;

mock.SetupAllProperties();
Assert.Equal(1, mock.Object.Value);
}

[Fact]
public void SetupAllProperties_should_override_regular_setups()
{
var mock = new Mock<IBar>();
mock.Setup(x => x.Value).Returns(1);

mock.SetupAllProperties();

Assert.Equal(0, mock.Object.Value);
}

private object GetValue() { return new object(); }

public interface IFoo
Expand Down