Mocking GetEnumerator using Moq

I am trying to make fun of the Variables interface in Microsoft.Office.Interop.Word assembly

var variables = new Mock<Variables>();
variables.Setup(x => x.Count).Returns(2);
variables.Setup(x => x.GetEnumerator()).Returns(TagCollection);

private IEnumerator TagCollection()
{
    var tag1 = new Mock<Variable>();
    tag1.Setup(x => x.Name).Returns("Foo");
    tag1.Setup(x => x.Value).Returns("Bar");

    var tag2 = new Mock<Variable>();
    tag2.Setup(x => x.Name).Returns("Baz");
    tag2.Setup(x => x.Value).Returns("Qux");

    yield return tag1.Object;
    yield return tag2.Object;
}

I have a code that looks like this:

// _variables is an instance of Variables interface
var tags = from variable in _variables.OfType<Variable>()
           where variable.Name == "Foo"
           select variable.Value;
var result = tags.ToList();

The last line in the code above throws a NullReferenceException. If I use the foreach loop to iterate through the _variables collection, I could easily access the variable layout objects. What am I doing wrong here?

+4
source share
1 answer

Try:

variables
    .As<IEnumerable>()
    .Setup(x => x.GetEnumerator()).Returns(TagCollection);

There are two different methods, one of which is specified in the base interface, and one of which is specified in Variables.

foreach , , . foreach public, , IEnumerable .

.OfType<Variable>() Linq, IEnumerable, . .

:

_variables.GetEnumerator();

((IEnumerable)_variables).GetEnumerator();

, Moq :

public class TheTypeMoqMakes : Variables 
{
  Enumerator Variables.GetEnumerator()
  {
    // Use return value from after
    // expression tree you provided with 'Setup' without 'As'.
    // If you did not provide one, just return null.
  }

  Enumerator IEnumerable.GetEnumerator()
  {
    // Use return value from after
    // expression tree you provided with 'Setup' with 'As<IEnumerable>'.
    // If you did not provide one, just return null.
  }

  // other methods and properties
}

, Moq null , Setup, , MockBehavior.Loose. MockBehavior.Strict.


, Variables interface hiding .

+7

All Articles