12

在问题的结尾: Using Moq to set indexers in C#,有人强调了我也遇到的问题。但他们没有找到解决办法。

具体来说,我正在尝试使用泛型It.IsAny<string>作为键的匹配器并通过It.IsAny<object>. 通过索引访问并设置值时,它永远不会匹配,也不会访问我的回调方法。所以我的单元测试失败了。

var stateTable = new HashTable;
var httpSession = new Mock<HttpSessionStateBase>();

//works via httpSession.Add(key, value);
httpSession.Setup(x => x.Add(It.IsAny<string>(), It.IsAny<object>()))
    .Callback((string index, object value) => {
        var i = index;
        var v = value;

            stateData[i] = v;
    });

//does not work via httpSession[key] = value;
httpSession.SetupSet(x => x[It.IsAny<string>()] = It.IsAny<object>())
    .Callback( (string index, object value) => {
        var i = index;
        var v = value;

        stateData[i] = v;
});

我正在使用最小起订量 4.0.10827

4

3 回答 3

10

以我的经验,这永远行不通,您不能将 It.IsAny 用作索引器表达式中的匹配器。但是,如果您在索引器中输入具体值,它将匹配。例如,以下确实有效:

httpSession.SetupSet(x => x["someValue"] = It.IsAny<object>())
    .Callback( (string index, object value) => {
        var i = index;
        var v = value;

        stateData[i] = v;
});
于 2011-06-09T17:31:46.410 回答
2

这是我为验证读取所做的。

_httpSessionStateBaseMock.VerifySet(x => x["keyname"] = It.IsAny<YourObject>(), Times.Once());

对于我刚刚读过的书

_httpSessionStateBaseMock.Verify(x => x["keyname"],Times.Once());
于 2011-08-02T13:45:55.620 回答
1

我不喜欢它,但我能够使用新的继承类来解决它。然后我覆盖索引器并调用一个可以模拟的虚拟方法。

public class HttpSessionStateBaseProxy : HttpSessionStateBase
{
    public virtual void SetItem(string key, object value)
    {
        base[key] = value;
    }
    public override object this[string name]
    {
        get
        {
            return base[name];
        }
        set
        {
            SetItem (name, value);
        }
    }

}

并且模拟是通过以下方式完成的:

Mock<HttpSessionStateBaseProxy> Session = new Mock<HttpSessionStateBaseProxy>(MockBehavior.Loose);
Session.CallBase = true;
Session.Setup(x => x.SetItem(It.IsAny<string>(),It.IsAny<object>()))
        .Callback<string,object>((string index, object value) =>
        {
            if (!this.SessionItems.Contains(index)) this.SessionItems.Add(index, value);
            else this.SessionItems[index] = value;


        });

        Session.Setup(s => s[It.IsAny<string>()]).Returns<string>(key =>
        {

            return this.SessionItems[key];

        });
于 2013-06-05T15:05:03.107 回答