在我的单元测试中,我需要更改之前被模拟的对象的值。例如:
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;
}
}
我想在SetCell
中测试Table
方法。
所以,首先我模拟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 :/
答案 0 :(得分:1)
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