Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Moq with Linq Any()

I have a setup similar to below:

    [TestMethod]
    public void NoIntegers()
    {
        Mock<IBar> mockBar = new Mock<IBar>(MockBehavior.Strict);
        Mock<IEnumerable<int>> mockIntegers = new Mock<IEnumerable<int>>(MockBehavior.Strict);

        mockBar
            .SetupGet(x => x.Integers)
            .Returns(mockIntegers.Object);

        mockIntegers
            .Setup(x => x.Any())
            .Returns(false);

        Assert.IsFalse(new Foo(mockBar.Object).AreThereIntegers());
    }

    public interface IBar
    {
        IEnumerable<int> Integers { get; }
    }

    public class Foo
    {
        private IBar _bar;

        public Foo(IBar bar)
        {
            _bar = bar;
        }

        public bool AreThereIntegers()
        {
            return _bar.Integers.Any();
        }
    }
}

When it runs it fails to initialise the mock

Test method NoIntegers threw exception: System.NotSupportedException: Expression references a method that does not belong to the mocked object: x => x.Any<Int32>()

I have tries adding It.IsAny() in a few forms:

mockIntegers
    .Setup(x => x.Any(It.IsAny<IEnumerable<int>>(), It.IsAny<Func<int, bool>>()))
    .Returns(false);

// No method with this signiture


mockIntegers
    .Setup(x => x.Any(It.IsAny<Func<int, bool>>()))
    .Returns(false);

// Throws: Test method NoIntegers threw exception: 
// System.NotSupportedException: 
// Expression references a method that does not belong to the mocked object:
//  x => x.Any<Int32>(It.IsAny<Func`2>())

What do I need to mock in order for this to run?

like image 848
BanksySan Avatar asked Nov 26 '13 13:11

BanksySan


1 Answers

Fixed!

Not pretty, but this is the mocking that's needed:

   [TestMethod]
    public void NoIntegers()
    {
        Mock<IBar> mockBar = new Mock<IBar>(MockBehavior.Strict);
        Mock<IEnumerable<int>> mockIntegers = new Mock<IEnumerable<int>>(MockBehavior.Strict);
        Mock<IEnumerator<int>> mockEnumerator = new Mock<IEnumerator<int>>(MockBehavior.Strict);
        mockBar
            .SetupGet(x => x.Integers)
            .Returns(mockIntegers.Object);

        mockIntegers
            .Setup(x => x.GetEnumerator())
            .Returns(mockEnumerator.Object);

        mockEnumerator.Setup(x => x.MoveNext()).Returns(false);

        mockEnumerator.Setup(x => x.Dispose());

        Assert.IsFalse(new Foo(mockBar.Object).AreThereIntegers());
    }

    public interface IBar
    {
        IEnumerable<int> Integers { get; }
    }

    public class Foo
    {
        private IBar _bar;

        public Foo(IBar bar)
        {
            _bar = bar;
        }

        public bool AreThereIntegers()
        {
            return _bar.Integers.Any();
        }
    }
like image 79
BanksySan Avatar answered Sep 27 '22 20:09

BanksySan