Moq -返回与参数不同的类型

本文关键字:类型 参数 返回 Moq | 更新日期: 2023-09-27 18:03:17

我有一个模拟(使用Moq),它接受IEnumerable<T>并从该集合(T)返回一个项目。在尝试设置模拟时,我遇到了这个问题:

mockCollectionsSelector.SetupSequence(s => s.SelectRandomFrom<Feat>(It.Is<IEnumerable<Feat>>(fs => fs.All(f => f.Name == FeatConstants.FavoredEnemy))))
            .Returns((IEnumerable<Feat> fs) => fs.ElementAt(1))

Cannot convert lambda expression because it is not a delegate type

在Moq中引用参数的所有示例都具有与传入的相同的返回类型,因此这可能甚至不可能-如果是这样,那么我将不得不找到不同的方法来做到这一点。否则,我不确定我在这里做错了什么。

Moq -返回与参数不同的类型

我通过将Feat类替换为int:

来简化代码。
using System.Collections.Generic;
using System.Linq;
using Moq;
using NUnit.Framework;
namespace Tests
{
    [TestFixture]
    public class Tests
    {
        [Test]
        public void ShouldDoSomething()
        {
            Mock<ICollectionSelector> mockCollectionsSelector = new Mock<ICollectionSelector>();
            mockCollectionsSelector
                .Setup(s => s.SelectRandomFrom(It.Is<IEnumerable<int>>(fs => fs.All(f => true))))
                .Returns((IEnumerable<int> fs) => fs.ElementAt(1));  
                //.Returns<IEnumerable<int>>(fs => fs.ElementAt(1)); // this also works and is more readable I guess
            var selector = mockCollectionsSelector.Object;
            var number = selector.SelectRandomFrom(new[] {1, 2, 3, 4, 5, 6, 7});
            Assert.IsTrue(number == 2);
        }
    }
    public interface ICollectionSelector
    {
        int SelectRandomFrom<T>(IEnumerable<T> @is);
    }
}

很好。"测试"通过了。也许你可以尝试升级你的Moq库到最新版本?我在。net 4.5.2上使用了4.2.1507.118