简体   繁体   English

Moq-从参数返回不同类型

[英]Moq - Return Different Type From Parameter

I have a mock (using Moq) that takes in an IEnumerable<T> and return an item from that collection ( T ). 我有一个模拟(使用Moq),它接受IEnumerable<T>并从该集合( T )返回一个项目。 When trying to set up a mock, I run into this issue: 尝试设置模拟时,我遇到了这个问题:

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

All the examples of referencing parameters in Moq have the same return type as what was passed in, so this might not even be possible - and if so, then I will have to find a different way to do this. Moq中所有引用参数的示例都具有与传入的返回类型相同的返回类型,因此,这甚至是不可能的-如果是这样,那么我将必须找到一种不同的方式来执行此操作。 Otherwise, I am not sure what I am doing wrong here. 否则,我不确定在这里我做错了什么。

I simplified your code by replacing Feat class with int: 我通过将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);
    }
}

It works fine. 工作正常。 The 'test' passes. “测试”通过。 Maybe try upgrading your Moq library to the latest version? 也许尝试将您的Moq库升级到最新版本? I used 4.2.1507.118 on .Net 4.5.2 我在.Net 4.5.2上使用4.2.1507.118

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

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