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()
        .Where(
            p => p.PropertyType.Name == "Mock`1"
        ).ToArray();
    return pis.First().GetGetMethod().Invoke(mockedObject, null) as Mock<T>;
}

hope that helps.

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

  1. Yes, well spotted. We looked for some existing way to do this and didn’t see it, and couldn’t find much in the way of docs for Moq.

Comments are closed.

Get the Moq Mock from a mock object

by Chris F Carroll read it in 1 min
2