I am trying to put a mocked Range
(which contains cells with values) inside the rows of a new Range
. But when I try to access a specific element from the Range
, a exception is thrown.
I've tried everything, does anyone have a idea what I am doing wrong here?
Exception
Message: Test method xxx.MockUtilsTest.MockRowsTest threw exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot apply indexing with [] to an expression of type 'Castle.Proxies.RangeProxy'
Test
[TestMethod]
public void MockRowsTest()
{
var row1 = MockUtils.MockCells("test_row_1", "test_row_1");
var row2 = MockUtils.MockCells("test_row_2", "test_row_2");
var range = MockUtils.MockRows(row1, row2);
Assert.IsNotNull(range);
Assert.AreEqual(2, range.Count);
Assert.IsNotNull(range.Rows);
Assert.AreEqual(2, range.Rows.Count);
Assert.AreSame(row1, range.Rows[1].Cells[1]); // exception is thrown here
Assert.AreSame(row2, range.Rows[2].Cells[1]);
Assert.AreEqual("test_row_1", range.Rows[1].Cells[1].Value2);
Assert.AreEqual("test_row_2", range.Rows[2].Cells[1].Value2);
}
MockUtils
public static Range MockCellValue2(Object value)
{
var cell = new Moq.Mock<Range>();
cell.Setup(c => c.Value2).Returns(value);
return cell.Object;
}
public static Range MockCells(params Object[] values)
{
var cells = new Moq.Mock<Range>();
for (int i = 0; i < values.Length; i++)
{
var cell = MockCellValue2(values[i]);
cells.SetupGet(c => c[i + 1, Moq.It.IsAny<Object>()]).Returns(cell);
}
var row = new Moq.Mock<Range>();
row.SetupGet(r => r.Cells).Returns(cells.Object);
row.SetupGet(r => r.Count).Returns(values.Length);
return row.Object;
}
public static Range MockRows(params Range[] rows)
{
var mergedRows = MergeRanges(rows);
var range = new Moq.Mock<Range>();
range.SetupGet(r => r.Count).Returns(rows.Length);
range.SetupGet(r => r.Rows).Returns(() => mergedRows);
range.Setup(r => r.GetEnumerator()).Returns(rows.GetEnumerator());
return range.Object;
}
public static Range MergeRanges(params Range[] ranges)
{
var range = new Moq.Mock<Range>();
for (int i = 0; i < ranges.Length; i++)
{
range.SetupGet(r => r[i + 1, Moq.It.IsAny<Object>()]).Returns(ranges[i]);
}
range.SetupGet(r => r.Count).Returns(ranges.Length);
range.Setup(r => r.GetEnumerator()).Returns(ranges.GetEnumerator());
return range.Object;
}