使用 Moq 通过任意键和值设置任意
在问题的最后: 在 C# 中使用 Moq 设置索引器,出现了一个问题,有人强调了我也遇到的一个问题。但他们没有找到解决办法。
具体来说,我尝试使用通用 It.IsAny
作为键的匹配器,并通过 It.IsAny
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
At the end of the question:
Using Moq to set indexers in C#, there was an issue that someone highlighted a problem that I am having as well. But they did not find a solution.
Specifically, I'm trying to use the generic It.IsAny<string>
as the matcher for the key and setting the value via It.IsAny<object>
. When accessing via an index and setting the value, it never matches and it does not access my call back method. And so my unit tests are failing.
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;
});
I'm using Moq 4.0.10827
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据我的经验,这永远不会起作用,您不能使用 It.IsAny 作为索引器表达式中的匹配器。但是,如果您在索引器中输入具体值,它将匹配。
例如,以下内容确实有效:
In my experience this never works, you cannot use the It.IsAny as a matcher in the indexer expression. However, it will match if you put a concrete value in the indexer.
For example, the following does work:
这就是我为验证阅读所做的事情。
对于我刚刚阅读的内容
This is what I did to verify the read.
for the reads I just went with
我不喜欢它,但我可以使用新的继承类来解决它。
然后,我重写索引器并调用可以模拟的虚拟方法。
嘲笑是通过以下方式完成的:
I don't like it but I was able to work around it using a new inherits class.
I then override the indexer and called a virtual method which can be mocked.
and the mocking is done by :