Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock an interface that extends IEnumerable

I'm using Moq and I have the following interface:

public interface IGameBoard : IEnumerable<PieceType>
{
    ...  
}
public class GameBoardNodeFactory
{
    public virtual GameBoardNode Create (int row, int column, IGameBoard gameBoard)
    {
        ...
    }
}

Then I have a test like this:

var clonedGameBoardMock = new Mock<IGameBoard> (MockBehavior.Loose);
var gameBoardNodeFactoryMock = new Mock<GameBoardNodeFactory> ();
gameBoardNodeFactoryMock.Setup (x =>
    x.Create (
        position.Row,
        position.Column,
        clonedGameBoardMock.Object)).Returns (new GameBoardNode { Row = position.Row, Column = position.Column });

But then gameBoardNodeFactoryMock.Object.Create (position.Row, position.Column, clonedGameBoardMock.Object) throws a NullReferenceException. I tried to create a mock for the IGameBoard such that it doesn't extend IEnumerable<PieceType> interface and then it works.

Any help is appreciated.

like image 670
Zoliqa Avatar asked Apr 05 '11 14:04

Zoliqa


1 Answers

You would need to create a Setup for GetEnumerator() if it's being called. Something like:

var mockPieces = new List<PieceType>;
clonedGameBoardMock.Setup(g => g.GetEnumerator()).Returns(mockPieces.GetEnumerator());

Note sure if that's the issue in this case, but worth noting if you ever need to mock IEnumerable<T>.

like image 76
Dan Bryant Avatar answered Oct 10 '22 23:10

Dan Bryant