如何MOQ索引属性

Ash*_*Ash 74 c# tdd moq mocking

我试图模拟对索引属性的调用.即我想moq以下:

object result = myDictionaryCollection["SomeKeyValue"];
Run Code Online (Sandbox Code Playgroud)

以及设定值

myDictionaryCollection["SomeKeyValue"] = myNewValue;
Run Code Online (Sandbox Code Playgroud)

我这样做是因为我需要模拟我的应用程序使用的类的功能.

有谁知道如何用MOQ做到这一点?我尝试过以下变化:

Dictionary<string, object> MyContainer = new Dictionary<string, object>();
mock.ExpectGet<object>( p => p[It.IsAny<string>()]).Returns(MyContainer[(string s)]);
Run Code Online (Sandbox Code Playgroud)

但那不编译.

我想用MOQ实现的目标是什么,有没有人有任何我可以做到这一点的例子?

Mik*_*ott 83

目前尚不清楚你要做什么,因为你没有展示模拟的声明.你想嘲笑一本字典吗?

MyContainer[(string s)] 是无效的C#.

这编译:

var mock = new Mock<IDictionary>();
mock.SetupGet( p => p[It.IsAny<string>()]).Returns("foo");
Run Code Online (Sandbox Code Playgroud)


was*_*ker 20

Ash,如果你想让HTTP Session模拟,那么这段代码可以完成这项工作:

/// <summary>
/// HTTP session mockup.
/// </summary>
internal sealed class HttpSessionMock : HttpSessionStateBase
{
    private readonly Dictionary<string, object> objects = new Dictionary<string, object>();

    public override object this[string name]
    {
        get { return (objects.ContainsKey(name)) ? objects[name] : null; }
        set { objects[name] = value; }
    }
}

/// <summary>
/// Base class for all controller tests.
/// </summary>
public class ControllerTestSuiteBase : TestSuiteBase
{
    private readonly HttpSessionMock sessionMock = new HttpSessionMock();

    protected readonly Mock<HttpContextBase> Context = new Mock<HttpContextBase>();
    protected readonly Mock<HttpSessionStateBase> Session = new Mock<HttpSessionStateBase>();

    public ControllerTestSuiteBase()
        : base()
    {
        Context.Expect(ctx => ctx.Session).Returns(sessionMock);
    }
}
Run Code Online (Sandbox Code Playgroud)


Vit*_*kov 9

正如您正确发现的那样,有不同的方法SetupGetSetupSet分别初始化getter和setter.虽然SetupGet旨在用于属性,而不是索引器,并且不允许您处理传递给它的键.确切地说,无论如何索引者SetupGet都会打电话Setup:

internal static MethodCallReturn<T, TProperty> SetupGet<T, TProperty>(Mock<T> mock, Expression<Func<T, TProperty>> expression, Condition condition) where T : class
{
  return PexProtector.Invoke<MethodCallReturn<T, TProperty>>((Func<MethodCallReturn<T, TProperty>>) (() =>
  {
    if (ExpressionExtensions.IsPropertyIndexer((LambdaExpression) expression))
      return Mock.Setup<T, TProperty>(mock, expression, condition);
    ...
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

要回答您的问题,以下是使用底层Dictionary存储值的代码示例:

var dictionary = new Dictionary<string, object>();

var applicationSettingsBaseMock = new Mock<SettingsBase>();
applicationSettingsBaseMock
    .Setup(sb => sb[It.IsAny<string>()])
    .Returns((string key) => dictionary[key]);
applicationSettingsBaseMock
    .SetupSet(sb => sb["Expected Key"] = It.IsAny<object>())
    .Callback((string key, object value) => dictionary[key] = value);
Run Code Online (Sandbox Code Playgroud)

如您所见,您必须明确指定用于设置索引器设置器的键.详细信息在另一个SO问题中描述:Moq是一个索引属性,并使用返回/回调中的索引值

  • 这就是我一直在寻找的!其他例子都不起作用 (3认同)

Jus*_*and 7

它并不困难,但它需要一点点找到它:)

var request = new Moq.Mock<HttpRequestBase>();
request.SetupGet(r => r["foo"]).Returns("bar");
Run Code Online (Sandbox Code Playgroud)


Ash*_*Ash -5

看来我试图用最小起订量做的事情是不可能的。

本质上,我试图最小起订量 HTTPSession 类型对象,其中设置为索引的项目的键只能在运行时确定。访问索引属性需要返回之前设置的值。这适用于基于整数的索引,但基于字符串的索引不起作用。