diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e2b11149..8464b93e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. The format is loosely based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). +## Unreleased + +#### Fixed + +* AmbiguousMatchException when setting up the property, that hides another one (@ishatalkin, #939) ## 4.13.0 (2019-08-31) diff --git a/src/Moq/ExpressionExtensions.cs b/src/Moq/ExpressionExtensions.cs index 2976964ef..981566fdc 100644 --- a/src/Moq/ExpressionExtensions.cs +++ b/src/Moq/ExpressionExtensions.cs @@ -320,7 +320,10 @@ internal static PropertyInfo GetReboundProperty(this MemberExpression expression // we "upgrade" to the derived property. if (property.DeclaringType != expression.Expression.Type) { - var derivedProperty = expression.Expression.Type.GetProperty(property.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + var derivedProperty = expression.Expression.Type + .GetMember(property.Name, MemberTypes.Property, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) + .Cast() + .SingleOrDefault(p => p.PropertyType == property.PropertyType); if (derivedProperty != null && derivedProperty.GetMethod.GetBaseDefinition() == property.GetMethod) { return derivedProperty; diff --git a/tests/Moq.Tests/HidePropertyFixture.cs b/tests/Moq.Tests/HidePropertyFixture.cs new file mode 100644 index 000000000..d4070ab5c --- /dev/null +++ b/tests/Moq.Tests/HidePropertyFixture.cs @@ -0,0 +1,35 @@ +// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. +// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. + +using Xunit; + +namespace Moq.Tests +{ + public class HidePropertyFixture + { + public class A + { + public string Prop { get; } + } + + public class B : A + { + public new virtual int Prop { get; } + } + + public class C : B + { + } + + [Fact] + public void SetupsDerivedProperty() + { + var mock = new Mock(); + var value = 5; + + mock.Setup(m => m.Prop).Returns(value); + + Assert.Equal(value, mock.Object.Prop); + } + } +}