简体   繁体   中英

Access input variable of lambda expression outside it's scope for Mocking Purpose in MOQ

I am using Moq for mocking a repository and want to use the parameter that was passed to the method of the mock object and return that parameter. Following is the example of what I want to do.

ItemRepo.Setup(ir => ir.Find(It.Is<Item>(item => Items.Any(i => i.Id.Equals(item.Id)))))
                .Returns(item);

OR

ItemRepo.Setup(ir => ir.Find(It.Is<Item>(item => Items.Any(i => i.Id.Equals(item.Id)))))
                .Returns(item.Id);

Here ItemRepo is the mock of ITemsRepository and Items is list that I am using to simulate insertion and deletion into the database. I am unable to access item variable that is the variable that will be passed to the find method of the mock object when this method will be called. I just want to return item that satisfied the given condition from this method. Thanks in advance.

Try getting the value from a function that when you're not testing just returns the value. eg item => GetItem(Items.Any(i => i.Id.Equals(item.Id))) You could also put the Items.Any(i => i...) into the GetItem function and just pass Items to that function.

private void Stuff()
{
ItemRepo.Setup(ir => FindItem(ir.Find(It.Is<Item>(item => Items.Any(i => i.Id.Equals(item.Id))))))
                .Returns(item)
}

private object FindItem(object p)
        {
            return p;
        }

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