如何模拟字典?
首先,我最好问我是否应该模拟字典?如果我应该如何实现这一目标?
我正在使用犀牛模拟。我查看了它的文档,发现它可以模拟 ArrayList。所以我在字典上尝试过,但没有成功。我收到错误,我没有调用虚拟方法bla bla...如果我不模拟它,会有问题吗?
First, I'd better ask if I should mock dictionaries? And if I should how can I achieve that?
I am using Rhino Mocks. I looked through its documentation and saw that it can mock ArrayList. So I tried it on Dictionary but no luck. I got the error that I'm not calling a virtual method bla bla... Will it be a problem if I don't mock it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只能模拟接口或具有虚拟方法的类:您无法模拟
Dictionary
,但可以模拟IDictionary
。这取决于您的情况,但构造一个真正的字典并用模拟对象填充它可能就足够了。
You can only mock interfaces, or classes with virtual methods: you can't mock a
Dictionary<K,V>
, but you can mock anIDictionary<K,V>
.It depends on your situation, but it might be enough to construct a real dictionary, and fill it with mock objects.
如果不知道您的具体测试场景,我不会模拟 .NET 框架类,因为您可以认为它们可以正常工作。
此规则的例外可能适用于允许访问外部资源(如 File 或 SQLConnection)的类,但这是因为您不想在单元测试中设置这些资源,而不是因为您不想测试这些类本身。
Without knowing your specific test scenario I wouldn't mock a .NET framework class, because you can take it as given that they work correctly.
Exceptions to this rule may apply to classes that give access to external ressources (like File or SQLConnection) but this is because you don't want to setup these ressources in your unit test, not because you don't want to test the classes themselves.
我可以向您保证,字典在 .Net 中工作得很好:)
我认为您在编写测试时需要务实,而不是试图模拟一切。因为你能走多远?你会如何嘲笑 int ?显然,边界线在哪里是可以讨论的,但我通常不会嘲笑:
I can assure you that the Dictionary works fine in .Net :)
I think you need to be pragmatic when writing your tests and not try to mock everything. Because how far can you go? How would you mock an int? Obviously it is discussable where is the border line, but I usually don't mock: