使用起订量设定在C#索引器 [英] Using Moq to set indexers in C#

查看:127
本文介绍了使用起订量设定在C#索引器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法搞清楚如何设置索引在C#中使用起订量。起订量文档弱,而我已经做了很多搜索...我想要做的是在溶液中的如何设置起订量索引属性

  VAR SomeClass的=新模拟< ISomeClass>(); 
someClass.SetupSet(O => o.SomeIndexedProperty [3] = 25);



我要修改上面的任何索引和任何值,所以我可以做类似的工作这样的:

  someClass.Object.SomeIndexedProperty [1] = 5; 

目前我有以下的,伟大的工程为索引属性的getter,但如果我设置值最小起订量忽略它:

  VAR someValues​​ = INT新[] {10,20,30,40}; 
VAR = SomeClass的新模拟< ISomeClass>();
someClass.Setup(O => o.SomeIndexedProperty [It.IsAny< INT>()])
.Returns< INT>(指数=> someValues​​ [指数]);

// Moq的不设置下面的值,因此断言失败!
someClass.Object.SomeIndexedProperty [3] = 25;
Assert.AreEqual(25,someClass.Object.SomeIndexedProperty [3]);


解决方案

我找到了解决我的问题。它需要在我的思想的转变......我一直在寻找使用NUnit的的断言来验证我的 SomeClass的模拟正在调用正确的值。



这似乎与起订量支持的方式做到这一点是使用 VerifySet 功能。一个人为的例子:

  someClass.Object.SomeIndexedProperty [3] = 25; 
someClass.VerifySet(模拟= GT; mock.SomeIndexedProperty [3] = 25);



单元测试通过,因为 SomeIndexedProperty [3] 设置为25,但在其他方面将失败。


I'm having trouble figuring out how to set indexers in C# with Moq. The Moq documentation is weak, and I've done a lot of searching... what I'd like to do is similar in the solution to How to Moq Setting an Indexed property:

var someClass = new Mock<ISomeClass>();
someClass.SetupSet(o => o.SomeIndexedProperty[3] = 25);

I want to modify the above to work for any index and any value so I can just do something like this:

someClass.Object.SomeIndexedProperty[1] = 5;

Currently I have the following, which works great for the indexed property getter, but if I ever set the value Moq ignores it:

var someValues = new int[] { 10, 20, 30, 40 };
var someClass = new Mock<ISomeClass>();
someClass.Setup(o => o.SomeIndexedProperty[It.IsAny<int>()])
    .Returns<int>(index => someValues[index]);

// Moq doesn't set the value below, so the Assert fails!
someClass.Object.SomeIndexedProperty[3] = 25;
Assert.AreEqual(25, someClass.Object.SomeIndexedProperty[3]);

解决方案

I found a solution to my problem. It requires a shift in my thinking... I had been looking to use NUnit's Assert to verify that the indexer setter in my someClass mock was being called with the correct value.

It seems that with Moq the supported way to do this is to use the VerifySet function. A contrived example:

someClass.Object.SomeIndexedProperty[3] = 25;
someClass.VerifySet(mock => mock.SomeIndexedProperty[3] = 25);

The unit test passes since SomeIndexedProperty[3] is set to 25, but would fail otherwise.

这篇关于使用起订量设定在C#索引器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆