Skip to content

Instantly share code, notes, and snippets.

@AlexZeitler
Created May 5, 2011 20:11
Show Gist options
  • Save AlexZeitler/957821 to your computer and use it in GitHub Desktop.
Save AlexZeitler/957821 to your computer and use it in GitHub Desktop.
Passing System.Type to Moq.As<T>
public override object CreateFake(Type firstInterfaceType, Type secondInterfaceType)
{
var closedFirstMockType = typeof(Mock<>).MakeGenericType(firstInterfaceType);
var closedSecondMockType = typeof (Mock<>).MakeGenericType(secondInterfaceType);
var objectProperty = closedFirstMockType.GetProperty("Object", closedFirstMockType);
var instance = Activator.CreateInstance(closedFirstMockType);
return objectProperty.GetValue(instance, null);
}
Tried:
var closedMockType = typeof(Mock<>).MakeGenericType(firstInterfaceType, secondInterfaceType);
but returns "The number of generic arguments provided doesn't equal the arity of the generic type definition."
@BjRo
Copy link

BjRo commented May 6, 2011

Haven't the code in front of me but isn't As<T> a static method on the Mock<T> class? If so you could get a methodinfo for it in order to invoke it...

@AlexZeitler
Copy link
Author

You're right. Next thing: setting up property behavior manually as in Rhino.Mocks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment