【问题标题】:How to change an object that was mocked?如何更改被模拟的对象?
【发布时间】:2017-04-15 03:43:56
【问题描述】:

在我的单元测试中,我需要更改之前模拟的对象的值。例如:

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;
    }
}

我想在Table 中测试SetCell 方法。

所以,首先我模拟Cell,然后创建一个Cell[,] 单元格数组,创建一个Table 传递单元格数组作为参数。

SetCell 不起作用,因为(我认为)我无法更改之前模拟的对象。我怎样才能改变它?

这是我的测试:

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 :/

【问题讨论】:

    标签: c# .net unit-testing testing moq


    【解决方案1】:

    Setup all the properties 以便他们可以更新

    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.SetupAllProperties();
            mock.Object.X = i;
            mock.Object.Y = j;
            mock.Object.Value = "";
    
            cells[i, j] = mock.Object;
        }
    }
    
    //...other code removed for brevity
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      相关资源
      最近更新 更多