1
votes

I have a mock (using Moq) that takes in an IEnumerable<T> and return an item from that collection (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. Otherwise, I am not sure what I am doing wrong here.

1
I concur with @gisek this should work. Could you show the implementation of the method SelectRandomFrom? - Daniel DuĊĦek
Considering that this is a mock, the implementation details don't matter - cidthecoatrack

1 Answers

1
votes

I simplified your code by replacing Feat class with 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? I used 4.2.1507.118 on .Net 4.5.2