NSubstitute: stubbing properties that aren’t known until run-time
The usual way to stub a property in NSubstitute is something like: -
myMockObject.SomeProperty.Returns(value)
But what if you only have the mock object as an untyped object, but you want to stub a method on it anyway? The NSubstitute documentation doesn’t tell you how to do that, but it can be done.
First, you need to get hold of a PropertyInfo via reflection, then you invoke it on the mock object: -
myProperty.GetMethod.Invoke(myMockObject, null)
This sets it as the “last call” in NSubstitute. So now you can use the substitution context to set the return value: -
SubstitutionContext.Current.LastCallShouldReturn(new ReturnValue(value), MatchArgs.Any)
It’s important that the above call immediately follows the Invoke(). Any code in between can change the “last call” in NSubstitute.
The same kind of thing can be done for methods, as opposed to properties. I leave that as an exercise for the reader.
Well, I hope that helps someone.