简体   繁体   English

返回正确结果的最小起订量设置方法

[英]Moq Setup Method to return correct result

Need help is it possible to manage Moq setup like this需要帮助是否可以像这样管理起订量设置

repositoryMock.Setup(s => s.Find(It.IsAny<object>())).Returns(() => DataList().FirstOrDefault(w => w.Id == It.IsAny<Guid>()));

Why I'm asking, because with this setup I always get return null, but if I put only to return DataList().FirstOrDefault(), it is returning correctly the first element in the list.为什么我要问,因为在这个设置中我总是得到 return null,但如果我只把 return DataList().FirstOrDefault(),它正确地返回列表中的第一个元素。 My question is how I can manage DataList with "n" elements where element which I need will be in the middle and when mock setup is run to return if element exists?我的问题是如何使用“n”个元素来管理 DataList,其中我需要的元素将位于中间,并且当元素存在时运行模拟设置以返回?

Updates更新

private IList<Data> DataList()
{
        List<Data> dataList = new List<Data> {

            new Data
            {
                Id =  new Guid("299cd2b5-ab47-4006-9a47-c35e4770e9b1"),

            },
            new Data
            {
                Id = new Guid("279cd2b5-ab47-4006-9a47-c35e4770e9b1"),

            }
        };
        return dataList;
    }

Kind Regards,亲切的问候,

如果你想至少返回一个对象。

repositoryMock.Setup(s => s.Find(It.IsAny<IBaseRepository>())).Returns(() => DataList().FirstOrDefault(w => w.Id == It.Is<Guid>()));

Capture the passed argument in the Returns delegate and use that to filter the listReturns委托中捕获传递的参数并使用它来过滤列表

repositoryMock
    .Setup(_ => _.Find(It.IsAny<object>()))
    .Returns((object arg) => {
        if(arg is Guid id)
            return DataList().FirstOrDefault(w => w.Id == id);
        return null;
    });

This assumes that the definition of the mocked member is IRepostory<T>.Find(object id) given the use of It.IsAny<object>() in the expectation expression.这假定IRepostory<T>.Find(object id)成员的定义是IRepostory<T>.Find(object id)给定在期望表达式中使用It.IsAny<object>()

If however the definition was IRepostory<T>.Find(Guid id) then the setup would be slightly different然而,如果定义是IRepostory<T>.Find(Guid id)那么设置会略有不同

repositoryMock
    .Setup(_ => _.Find(It.IsAny<Guid>()))
    .Returns((Guid id) => DataList().FirstOrDefault(w => w.Id == id));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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