Get the Moq Mock from a mock object

Update: See Vladimir’s comment below for the built in one-liner.

So there you in your code or possible your debugger and immediate window and you have a mock object and realise you want to change the setup but you didn’t keep a reference to the Mock<> …
So your first though is, no problem, you can cast your object to one of type Castle.Proxies.MyStronglyTypedProxyClass and voila you have access to the Mock property. Except that the compiler doesn’t recognise Castle.Proxies.MyStronglyTypedProxyClass as real class.
So then you try reflection to get hold of the Mock property. Which nearly works, but you get a System.Reflection.AmbiguousMatchException : Ambiguous match found. because there’s more than one property called Mock (one with and one without a generic parameter).
But this worked for me:

public static Mock<T> GetMockFromObject<T>(T mockedObject) where T : class
    PropertyInfo[] pis = mockedObject.GetType().GetProperties()
            p => p.PropertyType.Name == "Mock`1"
    return pis.First().GetGetMethod().Invoke(mockedObject, null) as Mock<T>;

hope that helps.

2 thoughts on “Get the Moq Mock from a mock object

Leave a Reply to Vladimir Smirnov Cancel reply

Your email address will not be published. Required fields are marked *