Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SetupAllObjectSets
public static Mock<IUnitOfWork> SetupAllObjectSets(this Mock<IUnitOfWork> mock)
{
var properties = typeof(IUnitOfWork).GetProperties();
foreach (var property in properties)
{
//IObjectSet<Of Something>
var genericType = property.PropertyType.GetGenericTypeDefinition();
if (genericType == typeof(System.Data.Objects.IObjectSet<>))
{
//Gets the <T> out of IObjectSet<T>
var modelType = property.PropertyType.GetGenericArguments().Single();
//Make a new FakeObjectSet<T>
var fakeObjectSetType = typeof(FakeObjectSet<>);
var constructed = fakeObjectSetType.MakeGenericType(modelType);
var newFakeObjectSet = Activator.CreateInstance(constructed);
//make expression of unitOfWork => unitOfWork.Property
var param = Expression.Parameter(typeof(IUnitOfWork));
var expression = Expression.Lambda(Expression.MakeMemberAccess(param, property), param);
// Get generic version of the mock.Setup method
var setup = mock.GetType().GetMethods().Single(d => d.Name == "Setup" && d.ContainsGenericParameters);
var typedSetup = setup.MakeGenericMethod(property.PropertyType);
// Run the Setup method with our property expression - unitOfWork.Setup(x => x.Property)
var returnedSetup = typedSetup.Invoke(mock, new[] { expression });
// Get the generic Returns method
var iReturns = typedSetup.ReturnType.GetInterfaces().Single(d => d.Name.StartsWith("IReturns`"));
var returns = iReturns.GetMethod("Returns", new Type[] { property.PropertyType });
// Run the returns method passing in our new fake object set - .Returns(newFakeObjectSet)
returns.Invoke(returnedSetup, new[] { newFakeObjectSet });
}
}
return mock;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment