Can you derive an action using Generics for use with TypeMock WhenCalled

116 views Asked by At

I have written an extension method helper for loading fake data into the DbContext

public static void RegisterFakeData<T>(this DbContext databaseContext, ObjectSet<T> action,   IEnumerable<T> fakeData) where T : class
{
    Isolate.WhenCalled(() => action).WillReturnCollectionValuesOf(fakeData.AsQueryable());
}

This works as desired but I was wondering if it is possible to derive the property on the dbcontext being passed in (action parameter) from the type of the fake data.

So if I'm setting the Customer property I just pass in a list of customers.

Current usage:

Isolate.Fake.StaticConstructor<DbContext>();
var databaseContext = Isolate.Fake.Instance<DbContext>();

databaseContext.RegisterFakeData(databaseContext.Customer, new List<Customer> { new Customer { CustID = "cust1", RegionCode = "region1"}})

Desired usage:

databaseContext.RegisterFakeData(new List<Customer> { new Customer { CustID = "cust1", RegionCode = "region1"}})
2

There are 2 answers

1
BarD On BEST ANSWER

I'm Bar from Typemock.

Because we don't fake any reflection methods you can use this workaround:

public void RegisterFakeData<T> (Context ctx,IEnumerable<T> list)
        {
            var name =typeof (T).Name;
            var mi = ctx.GetType().GetProperty(name).GetGetMethod();
            var args = new object[0] ;
            Isolate.WhenCalled(() =>(IEnumerable<T>)mi.Invoke(ctx,args)).WillReturnCollectionValuesOf(list);
        }
0
BarD On

You can use AsQueryable() :

Isolate.WhenCalled(() => (IEnumerable<T>)mi.Invoke(ctx,args)).WillReturnCollectionValuesOf
(list.AsQueryable());