Moq Unit Testing of Linq Find results in NullRefer

2019-09-10 13:43发布

问题:

I have recently started working on Moq for asp.net mvc. I get a NullReferenceException when the Find statement is executed. The code snippet is below.

There is a conflict when I try to unit test a Repository class method that has both linq Find and Linq Query statement. I believe that the last statement for dbContext.Setup in case of Students gets prioritized first. If dbContext.Setup for Find is placed after dbContext.Setup for Studnets, then Find works but it fails in Linq query for Student(dbContext.Students in query). Otherwise its the opposite. Any help or advice is appreciated. Thank you.

[TestMethod]
public void MyTestMethod() {
   ////Arrange
   var studentData = new List<Student> { 
      new Student { StudentId = 123, Name = "Demo1" },
       new Student { StudentId = 124, Name = "Demo2" }
   }.AsQueryable();

   mockStudentSet = new Mock<DbSet<Student>>();

   mockStudentSet.As<IQueryable<Student>>().Setup(m => m.Provider).Returns(studentData.Provider);
   mockStudentSet.As<IQueryable<Student>>().Setup(m => m.Expression).Returns(studentData.Expression);
   mockStudentSet.As<IQueryable<Student>>().Setup(m => m.ElementType).Returns(studentData.ElementType);
   mockStudentSet.As<IQueryable<Student>>().Setup(m => m.GetEnumerator()).Returns(studentData.GetEnumerator());


   dbContext.Setup(m => m.Students.Find(It.IsAny<long>())).Returns(new Student() { StudentId = 123 });

   dbContext.Setup(e => e.Students).Returns(mockStudentSet.Object);

}

//Repository Method that is being tested    
public StudentSummary GetStudentSummary(long StudentId) {

    StudentSummary studentSummary = new StudentSummary();
    var result = dbContext.Students.Find(StudentId);
    studentSummary.StudentName = result.Name;

    var myClass = (from mc in dbContext.MyClass
              join s in dbContext.Students on mc.StudentId equals s.StudentId
              where mc.StudentId == StudentId
              select new MyClass
              {
                  //
              }).ToList<MyClass>();

    //Rest of the code
}

The variable result in GetStudentSummary is null and gets a System.NullReferenceException there.