How to add an item to a Mock DbSet (using Moq)

后端 未结 2 979
悲&欢浪女
悲&欢浪女 2020-12-23 12:25

I\'m trying to set up a mock DbSet for testing purposes. I used the tutorial here, http://www.loganfranken.com/blog/517/mocking-dbset-queries-in-ef6/ and slightly modified i

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 13:19

    myDbSet is not real implementation of DbSet but a mock which means it's fake and it needs to be setup for all methods you need. The Add is not exception so it needs to be set up to do what you need otherwise it does nothing.

    Add something like the following and when the myDbSet.Add("d"); is called then the 'd' is added to the list and can be returned later.

    dbSet.Setup(d => d.Add(It.IsAny())).Callback((s) => sourceList.Add(s));
    

    Complete code

    private static DbSet GetQueryableMockDbSet(List sourceList) where T : class
    {
        var queryable = sourceList.AsQueryable();
    
        var dbSet = new Mock>();
        dbSet.As>().Setup(m => m.Provider).Returns(queryable.Provider);
        dbSet.As>().Setup(m => m.Expression).Returns(queryable.Expression);
        dbSet.As>().Setup(m => m.ElementType).Returns(queryable.ElementType);
        dbSet.As>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());
        dbSet.Setup(d => d.Add(It.IsAny())).Callback((s) => sourceList.Add(s));
    
        return dbSet.Object;
    }
    

    Output

    hello debug
    preCount = 3 postCount = 4
    

提交回复
热议问题