Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining methods with Moq

I'm attempting to mock and setup chained methods using Moq.

Here is the method I am trying to mock:

TeamMember teamMember = _unitOfWork
    .TeamMembers
    .Query()
    .ToList()
    .Where(t => t.AssociationCode.ToString() == code 
        && Crypto.EncryptStringAES(t.Id.ToString(), sharedSecret) == hash)
    .SingleOrDefault();

and here is where I attempt to mock it:

var unitOfWorkMock = new Mock<IUnitOfWork>();
var iQueryableMock = new Mock<IQueryable<TeamMember>>();
var iToListMock = new Mock<List<TeamMember>>();
var whereMock = new Mock<IList<TeamMember>>();
var singleMock = new Mock<IEnumerable<TeamMember>>();

unitOfWorkMock
    .Setup(u => u.TeamMembers
        .Query())
        .Returns(iQueryableMock.Object);

iQueryableMock
    .Setup(i => i.ToList())
        .Returns(iToListMock.Object); //This line throws the error

whereMock
    .Setup(w =>
            w.Where(It.IsAny<Func<TeamMember, bool>>()))
        .Returns(singleMock.Object);

singleMock
    .Setup(s =>
            s.SingleOrDefault())
        .Returns(new TeamMember()
        {
            Email = "[email protected]"
        });

When I run this test it gives me this error:

Expression references a method that does not belong to the mocked object: i => i.ToList<TeamMember>()

I have looked at this question already and have tried to do something similar, but I must be missing something.

I am new to this, so if anyone can help me out it will be greatly appreciated.

like image 939
Murray Avatar asked Oct 29 '25 17:10

Murray


1 Answers

Your method chain mocking looks fine, but your problem is that ToList is an extension method, which Moq cannot mock.

like image 198
Patrick Quirk Avatar answered Oct 31 '25 08:10

Patrick Quirk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!