Is there a way to generically mock the DbSet.Find method with Moq?

c# entity-framework entity-framework-6 generics moq

Accepted Answer

I've thought about this for a long, and I believe I've discovered the "best" answer at this time. I just have a string of if statements that explicitly examine the extension method's type. Then I cast to the type I need to set the find behavior and cast it back to generic when I'm done. Although merely pseudo-generic, there aren't any better options in my opinion.

        if (typeof(T) == typeof(MyFirstSet))
        {
            mockDbSet.Setup(x => x.Find(It.IsAny<object[]>())).Returns<object[]>(x => (sourceList as List<MyFirstSet>).FirstOrDefault(y => y.MyFirstSetKey == (Guid)x[0]) as T);
        }
        else if (typeof(T) == typeof(MySecondSet))
        {
            mockDbSet.Setup(x => x.Find(It.IsAny<object[]>())).Returns<object[]>(x => (sourceList as List<MySecondSet>).FirstOrDefault(y => y.MySecondSetKey == (Guid)x[0]) as T);
        }
        ...       
5
10/4/2016 8:37:27 PM

Popular Answer

There isn't a "best practise" response to this question that I'm aware of, but this is how I've gone about it. I've included a choice parameter in theAsDbSet technique that determines the main key, followed by theFind approach is simple to sketch up.

public static DbSet<T> AsDbSet<T>(this List<T> sourceList, Func<T, object> primaryKey = null) where T : class
{
    //all your other stuff still goes here

    if (primaryKey != null)
    {
        mockSet.Setup(set => set.Find(It.IsAny<object[]>())).Returns((object[] input) => sourceList.SingleOrDefault(x => (Guid)primaryKey(x) == (Guid)input.First()));
    }

    ...
}

Assuming a single GUID as the main key was how you were working when I wrote this, but the general idea should be simple enough to modify if you need additional flexibility for composite keys, etc.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow