简体   繁体   English

如何在单元测试中模拟 Automapper ProjectTo<> 方法?

[英]How to mock Automapper ProjectTo<> method in Unit Tests?

I am using the ProjectTo<T> method to get data from the DB.我正在使用ProjectTo<T>方法从数据库中获取数据。

names = _mapper.ProjectTo<ItemNameDto>(query).ToList();

In the unit tests I would like to mock this method to return a specific collection.在单元测试中,我想模拟这个方法来返回一个特定的集合。

Based on the second answer to this question - I figured out I need to pass all parameters to the setup.基于这个问题的第二个答案 - 我发现我需要将所有参数传递给设置。

When I pass null to the second parameter - the setup is ok, but when I pass null to the third one - the setup does not return the collection I want.当我将 null 传递给第二个参数时 - 设置没问题,但是当我将null传递给第三个参数时 - 设置不会返回我想要的集合。

What value should I pass to the Expression parameter in this particular case?在这种特殊情况下,我应该将什么值传递给 Expression 参数? I really wouldn't like to leave it with It.IsAny<> because it seems too broad to me.我真的不想把它留在It.IsAny<>因为它对我来说似乎太宽泛了。 I would like to write a setup which reflects exactly my use case.我想编写一个完全反映我的用例的设置。

_mapperMock
    .Setup(c => c.ProjectTo(
        It.Is<IQueryable<Item>>(x => x.HaveTheSameElements(filteredItems)),
        It.IsAny<object>(),
        It.IsAny<Expression<Func<ItemNameDto, object>>[]>()))
    .Returns(filteredItemNameDtos.AsQueryable());

This is the method signature I would like to setup.这是我想设置的方法签名。

IQueryable<TDestination> ProjectTo<TDestination>(IQueryable source, object parameters = null, params Expression<Func<TDestination, object>>[] membersToExpand);

To mock a call to ProjectTo where no membersToExpand are provided, you should use It.Is :嘲笑一个呼叫ProjectTo在没有membersToExpand提供,你应该使用It.Is

_mapperMock
    .Setup(c => c.ProjectTo(
        It.Is<IQueryable<Item>>(x => x.HaveTheSameElements(filteredItems)),
        It.IsAny<object>(),
        It.Is<Expression<Func<ItemNameDto, object>>[]>(x => x.Length == 0)))
    .Returns(filteredItemNameDtos.AsQueryable());

x => x.Length == 0 indicates an empty array, which the framework instantiates when no params have been passed. x => x.Length == 0表示一个空数组,框架在没有传递params时实例化它。

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

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