From 4d64fcea02d58b4c1dcca159209ccf07d245b213 Mon Sep 17 00:00:00 2001 From: stakx Date: Sat, 19 Oct 2019 18:14:38 +0200 Subject: [PATCH] Introduce `property.Can{Read,Write}` extension methods --- src/Moq/Extensions.cs | 30 +++++++++++++++++++++ src/Moq/Interception/InterceptionAspects.cs | 6 ++--- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/Moq/Extensions.cs b/src/Moq/Extensions.cs index d8ee7c748..9b20f2782 100644 --- a/src/Moq/Extensions.cs +++ b/src/Moq/Extensions.cs @@ -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; + } + } + /// /// Gets the default value for the specified type. This is the Reflection counterpart of C#'s operator. /// diff --git a/src/Moq/Interception/InterceptionAspects.cs b/src/Moq/Interception/InterceptionAspects.cs index 256805922..682e20b7e 100644 --- a/src/Moq/Interception/InterceptionAspects.cs +++ b/src/Moq/Interception/InterceptionAspects.cs @@ -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); @@ -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) =>