VerifySet throws TargetInvocationException when constructer refers to itself
The exception: System.Reflection.TargetInvocationException with the message " Exception has been thrown by the target of an invocation."
Is thrown during a call to VerifySet when code in a classes constructor references a property of this
Steps to Reproduce
This code reproduces the exception
[TestMethod]
public void Broken_moq()
{
var sut = Mock.Of<Example>();
Mock.Get(sut).VerifySet(x => x.A = "A", Times.Never);
}
public class Example
{
public virtual string A { get; set; }
public virtual string B { get; set; }
public Example()
{
A = "";
B = this.A;
}
}
Expected Behavior
The test above should run without throwing an exception
Exception with Stack Trace
Recorder.Intercept(Invocation invocation) line 413
Interceptor.Intercept(IInvocation underlying) line 218
AbstractInvocation.Proceed()
ExampleProxy_1.get_A()
Example.ctor() line 124
ExampleProxy_1.ctor(IInterceptor[] )
--- End of inner exception stack trace ---
RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
ProxyGenerator.CreateClassProxyInstance(Type proxyType, List`1 proxyArguments, Type classToProxy, Object[] constructorArguments)
ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
CastleProxyFactory.CreateProxy(Type mockType, IInterceptor interceptor, Type[] interfaces, Object[] arguments) line 110
ActionObserver.CreateProxy(Type type, Object[] ctorArgs, MatcherObserver matcherObserver, Recorder& recorder) line 275
ActionObserver.ReconstructExpression[T](Action`1 action, Object[] ctorArgs) line 53
Mock`1.VerifySet(Action`1 setterExpression, Func`1 times) line 1236
Version Info
4.20.70
Due to lack of recent activity, this issue has been labeled as 'stale'. It will be closed if no further activity occurs within 30 more days. Any new comment will remove the label.
Invoking virtual members from a constructor is pretty much an anti-pattern.
There seems to be some support for that but I don't even know why supporting that (however imperfectly) would be a good thing, TBH.
Due to lack of recent activity, this issue has been labeled as 'stale'. It will be closed if no further activity occurs within 30 more days. Any new comment will remove the label.
This issue will now be closed since it has been labeled 'stale' without activity for 30 days.
