Moqing Entity Framework 6 .Include() using DbSet<>

前端 未结 5 969
南笙
南笙 2020-12-07 17:47

I\'d like to give the background to this question. Skip if you like. For quite a while I\'ve paid close attention to the on going debates on stackoverflow and elsewhere rega

5条回答
  •  旧时难觅i
    2020-12-07 18:18

    I managed to mock Include in Moq with a generic approach. Albeit this doesn't cover all usages of Include(), only with string and Expression, but it suited my needs:

    public Mock> SetupMockSetFor(Expression>> selector) where T : class
        {
            var mock = new Mock>();
    
            mock.ResetCalls();
    
            this.EntitiesMock.Setup(m => m.Set()).Returns(mock.Object);
            this.EntitiesMock.Setup(selector).Returns(mock.Object);
    
            mock.Setup(x => x.Include(It.IsAny())).Returns(mock.Object);
    
            try
            {
                mock.Setup(x => x.Include(It.IsAny>>()))
                    .Returns(mock.Object);
            }
            catch
            {
                // Include only applies to some objects, ignore where it doesn't work
            }
    
            return mock;
        }
    

    test usage:

            var mockCourseSet = SetupMockSetFor(entities => entities.Courses);
    

    In service method:

    var foundCourses = dbContext.Courses.Include(c => c.CourseParticipants).Where(c => c.Id = courseId)
    

提交回复
热议问题