用Moq链接方法

时间:2015-07-30 19:05:29

标签: c# unit-testing mocking moq

我试图使用Moq来模拟和设置链式方法。

这是我试图模拟的方法:

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

这是我试图嘲笑的地方:

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 = "Test@TeamMember.com"
        });

当我运行此测试时,它会给我这个错误:

  

Expression引用一个不属于模拟对象的方法:i => i.ToList<TeamMember>()

我已经看过this question,并试图做类似的事情,但我必须遗漏一些东西。

我是新手,所以如果有人能帮助我,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

您的方法链模拟看起来很好,但您的问题是ToListextension methodMoq cannot mock