【发布时间】:2010-03-03 16:18:40
【问题描述】:
我正在尝试使用模拟来验证是否已设置索引属性。这是一个带索引的最小起订量对象:
public class Index
{
IDictionary<object ,object> _backingField
= new Dictionary<object, object>();
public virtual object this[object key]
{
get { return _backingField[key]; }
set { _backingField[key] = value; }
}
}
首先,尝试使用Setup():
[Test]
public void MoqUsingSetup()
{
//arrange
var index = new Mock<Index>();
index.Setup(o => o["Key"]).Verifiable();
// act
index.Object["Key"] = "Value";
//assert
index.Verify();
}
...失败了 - 它必须针对 get{} 进行验证
所以,我尝试使用SetupSet():
[Test]
public void MoqUsingSetupSet()
{
//arrange
var index = new Mock<Index>();
index.SetupSet(o => o["Key"]).Verifiable();
}
... 给出运行时异常:
System.ArgumentException : Expression is not a property access: o => o["Key"]
at Moq.ExpressionExtensions.ToPropertyInfo(LambdaExpression expression)
at Moq.Mock.SetupSet(Mock mock, Expression`1 expression)
at Moq.MockExtensions.SetupSet(Mock`1 mock, Expression`1 expression)
实现此目的的正确方法是什么?
【问题讨论】:
-
为什么要在这种情况下使用模拟?您要测试的是什么?为什么不直接测试 Index 类?
-
这是一个我真的很想模拟的带有索引属性的接口。我要求使用具有虚拟属性的具体对象来简化问题。
-
好的。更有意义:-)