简体   繁体   中英

Cannot get DbSet.Find to work with Moq (Using the Entity-Framework)

For some reason this code keeps failing. Anyone that can tell me why:

        var activeLoans = new List<ActiveLoan> {
            new ActiveLoan{
               ID = 1,
               CaseType = "STL",
               LoanCode = 0
            },
            new ActiveLoan{
               ID = 2,
               CaseType = "STL",
               LoanCode = 0
            },
            new ActiveLoan{
               ID = 3,
               CaseType = "STL",
               LoanCode = 0
            }
        }.AsQueryable();

        var activeLoanMockSet = new Mock<DbSet<ActiveLoan>>(); 
        activeLoanMockSet.As<IQueryable<ActiveLoan>>().Setup(m => m.Provider).Returns(activeLoans.Provider);
        activeLoanMockSet.As<IQueryable<ActiveLoan>>().Setup(m => m.Expression).Returns(activeLoans.Expression);
        activeLoanMockSet.As<IQueryable<ActiveLoan>>().Setup(m => m.ElementType).Returns(activeLoans.ElementType);
        activeLoanMockSet.As<IQueryable<ActiveLoan>>().Setup(m => m.GetEnumerator()).Returns(activeLoans.GetEnumerator());
        mockContext.Setup(c => c.ActiveLoans).Returns(activeLoanMockSet.Object);


        // This is the line that fails
        Assert.AreNotEqual(mockContext.Object.ActiveLoans.Find( 1 ), null);

When I say fail i mean that the unit test that this is a part of fails.

I think you need to also setup the IDbSet::Find .

activeLoanMockSet.Setup(m => m.Find(It.IsAny<object[]>()))
    .Returns<object[]>(ids => activeLoans.FirstOrDefault(d => d.ID == (int)ids[0]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM