vendredi 14 avril 2017

How to change an object that was mocked?

In my Unit Test I need to change the value of the object that was mocked before. For example:

public class Cell
{
    public int X { get; set; }
    public int Y { get; set; }
    public string Value { get; set; }
}

public class Table
{
    private Cell[,] Cells { get; }

    public Table(Cell[,] cells)
    {
        Cells = cells;
    }

    public void SetCell(int x, int y, string value)
    {
        Cells[x, y].Value = value;
    }
}

I want to test SetCell method in Table.

So, first I mock Cell, then I create a Cell[,] array of cells, create a Table passing array of cells as a parameter.

SetCell doesn't work, because (I think) I can't change the object that was mocked before. How can I change it?

Here's my test:

        ICell[,] cells = new ICell[3, 4];
        for (int i = 0; i < cells.GetLength(0); i++)
        {
            for (int j = 0; j < cells.GetLength(1); j++)
            {
                var mock = new Mock<ICell>();
                mock.Setup(m => m.X).Returns(i);
                mock.Setup(m => m.Y).Returns(j);
                mock.Setup(m => m.Value).Returns("");

                cells[i, j] = mock.Object;
            }
        }            


        ITable table = new Table(cells);
        table.SetCell(0, 0, "TEST"); // Cannot change it here :/

Aucun commentaire:

Enregistrer un commentaire