Skip to content

Commit

Permalink
Introduce property.Can{Read,Write} extension methods
Browse files Browse the repository at this point in the history
  • Loading branch information
stakx committed Oct 19, 2019
1 parent dd2578a commit 4d64fce
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
30 changes: 30 additions & 0 deletions src/Moq/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,36 @@ public static bool CanCreateInstance(this Type type)
return type.IsValueType || type.GetConstructor(Type.EmptyTypes) != null;
}

public static bool CanRead(this PropertyInfo property, out MethodInfo getter)
{
if (property.CanRead)
{
getter = property.GetGetMethod(nonPublic: true);
Debug.Assert(getter != null);
return true;
}
else
{
getter = null;
return false;
}
}

public static bool CanWrite(this PropertyInfo property, out MethodInfo setter)
{
if (property.CanWrite)
{
setter = property.GetSetMethod(nonPublic: true);
Debug.Assert(setter != null);
return true;
}
else
{
setter = null;
return false;
}
}

/// <summary>
/// Gets the default value for the specified type. This is the Reflection counterpart of C#'s <see langword="default"/> operator.
/// </summary>
Expand Down
6 changes: 2 additions & 4 deletions src/Moq/Interception/InterceptionAspects.cs
Original file line number Diff line number Diff line change
Expand Up @@ -314,9 +314,8 @@ public static bool Handle(Invocation invocation, Mock mock)
object propertyValue;

Setup getterSetup = null;
if (property.CanRead)
if (property.CanRead(out var getter))
{
var getter = property.GetGetMethod(true);
if (ProxyFactory.Instance.IsMethodVisible(getter, out _))
{
propertyValue = CreateInitialPropertyValue(mock, getter);
Expand All @@ -336,9 +335,8 @@ public static bool Handle(Invocation invocation, Mock mock)
}

Setup setterSetup = null;
if (property.CanWrite)
if (property.CanWrite(out var setter))
{
MethodInfo setter = property.GetSetMethod(nonPublic: true);
if (ProxyFactory.Instance.IsMethodVisible(setter, out _))
{
setterSetup = new AutoImplementedPropertySetterSetup(expression, setter, (newValue) =>
Expand Down

0 comments on commit 4d64fce

Please sign in to comment.