我试图使用模拟来验证索引属性是否已设置。下面是带索引的起订量,能够对象:如何设置索引属性
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();
}
...它给出了一个runtim e例外:
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类? – 2010-03-03 16:24:25
这是一个我真的想要模拟的索引属性的接口。我问了一个具有虚拟属性的具体对象来简化问题。 – 2010-03-03 16:27:46
好的。更有意义:-) – 2010-03-03 16:32:15