Skip to content

Commit

Permalink
Merge pull request devlooped#1155 from stakx/indexers
Browse files Browse the repository at this point in the history
Fix `InvalidOperationException` when mocking class with overloaded
property/indexer in base class.
  • Loading branch information
stakx committed Apr 9, 2021
2 parents b7b0727 + b231141 commit a6fde8b
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ 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

* Issue mocking VB.NET class with overloaded property/indexer in base class (@myurashchyk, #1153)


## 4.16.1 (2021-02-23)

#### Added
Expand Down
7 changes: 6 additions & 1 deletion src/Moq/ExpressionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -362,10 +362,15 @@ internal static PropertyInfo GetReboundProperty(this MemberExpression expression
// we "upgrade" to the derived property.
if (property.DeclaringType != expression.Expression.Type)
{
var parameterTypes = new ParameterTypes(property.GetIndexParameters());
var derivedProperty = expression.Expression.Type
.GetMember(property.Name, MemberTypes.Property, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Cast<PropertyInfo>()
.SingleOrDefault(p => p.PropertyType == property.PropertyType);
.SingleOrDefault(p =>
{
return p.PropertyType == property.PropertyType
&& new ParameterTypes(p.GetIndexParameters()).CompareTo(parameterTypes, true, false);
});
if (derivedProperty != null)
{
if ((derivedProperty.CanRead(out var getter) && getter.GetBaseDefinition() == property.GetGetMethod(true)) ||
Expand Down
33 changes: 33 additions & 0 deletions tests/Moq.Tests.VisualBasic/IssueReports.vb
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,37 @@ Public Class IssueReports
End Interface
End Class

Public Class Issue1153

<Fact>
Public Sub Indexer_overload_can_be_distinguished_from_property_when_mocking_declaring_class()
Dim mock = New Mock(Of MyVBClassBase)()
mock.Setup(Function(m) m.Prop).Returns(True)
End Sub

<Fact>
Public Sub Indexer_overload_can_be_distinguished_from_property_when_mocking_subclass_of_declaring_class()
Dim mock = New Mock(Of MyVBClass)()
mock.Setup(Function(m) m.Prop).Returns(True)
End Sub

Public Class MyVBClassBase
Public Overridable ReadOnly Property Prop() As Boolean
Get
Return True
End Get
End Property
Public Overridable ReadOnly Property Prop(ByVal userID As Guid) As Boolean
Get
Return False
End Get
End Property
End Class

Public Class MyVBClass
Inherits MyVBClassBase
End Class

End Class

End Class

0 comments on commit a6fde8b

Please sign in to comment.