What you are looking for are Linq expressions. Here's an example of creating a resource membership expression in action.
Using this class
public class ExampleClass { public virtual string ExampleProperty { get; set; } public virtual List<object> ExampleListProperty { get; set; } }
The following tests demonstrate dynamic access to these properties using the Linq.Expression classes.
[TestClass] public class UnitTest1 { [TestMethod] public void SetupDynamicStringProperty() { var dynamicMock = new Mock<ExampleClass>();
EDIT
You take a step too far with this code. This code creates a method with the signature of the required lambda, and then executes it (.Invoke). Then you try to pass the result of the object (hence a compilation error) to the setting for Moq. Moq will execute the execution and connect to you as soon as you tell how to proceed (hence the lambda). If you use the lambda expression I created, it will build what you need.
var funcType = typeof (Func<>).MakeGenericType(new Type[] {TableType, typeof(object)}); var lambdaMethod = typeof (Expression).GetMethod("Lambda"); var lambdaGenericMethod = lambdaMethod.MakeGenericMethod(funcType); var lambdaExpression = lambdaGenericMethod.Invoke(body, parameter);
Do it instead
var parameter = Expression.Parameter( TableType ); var body = Expression.PropertyOrField( parameter, "PutYourPropertyHere" ); var lambdaExpression = Expression.Lambda<Func<ExampleClass, object>>( body, parameter ); instance.Setup(lambdaExpression).Returns(inMemoryTable);
EDIT
Took a hit on GetMockContext fix. Pay attention to a few changes (I marked each line). I think this is closer. I am wondering if InMemoryTable inherits from DataContext? If not, the method signature will be incorrect.
public static object GetMockContext<T>() where T: DataContext { Type contextType = typeof (T); var instance = new Mock<T>();
Hope this helps!
source share