是什么导致此异常?我正在尝试使用Moq模拟Microsoft.Office.Interop.Excel.Range。我想在其中嵌套另一个模拟的Range。但是,当我尝试访问嵌套异常时,将引发异常。

例外


  无法将[]的索引应用于类型的表达式
  'Castle.Proxies.RangeProxy'




[TestMethod]
public void RangeProxyIndexTest()
{
    // creating first range
    var cell1 = new Moq.Mock<Range>();
    cell1.Setup(c => c.Value2).Returns("1");

    var range1Mock = new Moq.Mock<Range>();
    range1Mock.SetupGet(r => r[1, Moq.It.IsAny<Object>()]).Returns(cell1.Object);
    var range1 = range1Mock.Object;

    // creating second range
    var cell2 = new Moq.Mock<Range>();
    cell2.Setup(c => c.Value2).Returns("2");

    var range2Mock = new Moq.Mock<Range>();
    range2Mock.SetupGet(r => r[1, Moq.It.IsAny<Object>()]).Returns(cell2.Object);
    var range2 = range2Mock.Object;

    // merging both ranges into 1
    var range3Mock = new Moq.Mock<Range>();
    range3Mock.SetupGet(r => r[1, Moq.It.IsAny<Object>()]).Returns(range1);
    range3Mock.SetupGet(r => r[2, Moq.It.IsAny<Object>()]).Returns(range2);
    var range3 = range3Mock.Object;

    // testing succeeds
    Assert.AreEqual("1", range1[1].Value2);
    Assert.AreSame(range1, range3[1]);
    Assert.AreEqual("2", range2[1].Value2);
    Assert.AreSame(range2, range3[2]);

    // exceptions are thrown here
    Assert.AreEqual("1", range3[1][1].Value2);
    Assert.AreEqual("2", range3[2][1].Value2);
}

最佳答案

尽管情况有所不同,但导致此异常的原因与other question you have opened.完全相同

将您的验证部分更改为:

Assert.AreEqual("1", (range3[1] as Range)[1].Value2);
Assert.AreEqual("2", (range3[2] as Range)[1].Value2);


有关更多信息,请阅读this answer.

关于c# - 无法将[]的索引应用于类型'CaSTLe.Proxies.RangeProxy'的表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50640057/

10-12 13:20