我试图模拟对索引属性的调用.即我想moq以下:
object result = myDictionaryCollection["SomeKeyValue"];
以及设定值
myDictionaryCollection["SomeKeyValue"] = myNewValue;
我这样做是因为我需要模拟我的应用程序使用的类的功能.
有谁知道如何用MOQ做到这一点?我尝试过以下变化:
DictionaryMyContainer = new Dictionary (); mock.ExpectGet
但那不编译.
我想用MOQ实现的目标是什么,有没有人有任何我可以做到这一点的例子?
目前尚不清楚你要做什么,因为你没有展示模拟的声明.你想嘲笑一本字典吗?
MyContainer[(string s)]
是无效的C#.
这编译:
var mock = new Mock(); mock.SetupGet( p => p[It.IsAny ()]).Returns("foo");
Ash,如果你想让HTTP Session模拟,那么这段代码可以完成这项工作:
////// HTTP session mockup. /// internal sealed class HttpSessionMock : HttpSessionStateBase { private readonly Dictionaryobjects = new Dictionary (); public override object this[string name] { get { return (objects.ContainsKey(name)) ? objects[name] : null; } set { objects[name] = value; } } } /// /// Base class for all controller tests. /// public class ControllerTestSuiteBase : TestSuiteBase { private readonly HttpSessionMock sessionMock = new HttpSessionMock(); protected readonly MockContext = new Mock (); protected readonly Mock Session = new Mock (); public ControllerTestSuiteBase() : base() { Context.Expect(ctx => ctx.Session).Returns(sessionMock); } }
正如您正确发现的那样,有不同的方法SetupGet
并SetupSet
分别初始化getter和setter.虽然SetupGet
旨在用于属性,而不是索引器,并且不允许您处理传递给它的键.确切地说,无论如何索引者SetupGet
都会打电话Setup
:
internal static MethodCallReturnSetupGet (Mock mock, Expression > expression, Condition condition) where T : class { return PexProtector.Invoke >((Func >) (() => { if (ExpressionExtensions.IsPropertyIndexer((LambdaExpression) expression)) return Mock.Setup (mock, expression, condition); ... } ... }
要回答您的问题,以下是使用底层Dictionary
存储值的代码示例:
var dictionary = new Dictionary(); var applicationSettingsBaseMock = new Mock (); applicationSettingsBaseMock .Setup(sb => sb[It.IsAny ()]) .Returns((string key) => dictionary[key]); applicationSettingsBaseMock .SetupSet(sb => sb["Expected Key"] = It.IsAny
如您所见,您必须明确指定用于设置索引器设置器的键.详细信息在另一个SO问题中描述:Moq是一个索引属性,并使用返回/回调中的索引值
它并不困难,但它需要一点点找到它:)
var request = new Moq.Mock(); request.SetupGet(r => r["foo"]).Returns("bar");