Skip to content

Allow hidden methods to be mocked #22

tkellogg opened this Issue Jul 17, 2012 · 3 comments

3 participants

Moq Team member

The primary example of this is mocking IEnumerable:

interface IMyCollection : IEnumerable<Item>

The IEnumerable<Item>.GetEnumerator() actually hides IEnumerator.GetEnumerator(). As a result, this setup code only sets up the generic version

var mock = new Mock<IMyCollection>();
mock.Setup(x => x.GetEnumerator()).Returns(list.GetEnumerator())

When you use Linq methods, like mock.Object.FirstOrDefault(), it tries to use the IEnumerable.GetEnumerator() method. We need a way to conveniently do this setup.

I propose that we also setup all hidden methods/properties by default. So if you do that mock.Setup(x => x.GetEnumerator()), it just works.

I also propose that we support a cast in the Setup expression, mock.Setup(x => ((IEnumerable)x).GetEnumerator()) to be specific about which method we're talking about.

sloncho commented May 29, 2013

Interesting, this works. What do I miss?

        public interface IMyCollection : IEnumerable<int>


        public void TEST()
            var list = new List<int> {1, 2, 3};
            var mock = new Mock<IMyCollection>(MockBehavior.Strict);
            mock.Setup(m => m.GetEnumerator()).Returns(list.GetEnumerator());

            var first = mock.Object.First();

sloncho commented May 29, 2013

Also, there is already a mechanism to get another interface and set it:

var mock = new Mock<IMyCollection>(MockBehavior.Strict);
var ienum = mock.As<IEnumerable>();
ienum.Setup(e => e.GetEnumerator()).Returns(list.GetEnumerator());

Real world example of when some syntactic sugar would be nice.

        var refs = new Mock<References>();
        refs.Setup(r => r.GetEnumerator()).Returns(ReferenceList());
        refs.As<IEnumerable>().Setup(r => r.GetEnumerator()).Returns(ReferenceList);

This is a situation where to properly set up the mock, we need to repeat ourselves and provide the same implementation twice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.