如何模拟字典?

发布于 2024-10-07 12:13:56 字数 140 浏览 3 评论 0原文

首先,我最好问我是否应该模拟字典?如果我应该如何实现这一目标?

我正在使用犀牛模拟。我查看了它的文档,发现它可以模拟 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

挽手叙旧 2024-10-14 12:13:56

您只能模拟接口或具有虚拟方法的类:您无法模拟 Dictionary,但可以模拟 IDictionary

这取决于您的情况,但构造一个真正的字典并用模拟对象填充它可能就足够了。

You can only mock interfaces, or classes with virtual methods: you can't mock a Dictionary<K,V>, but you can mock an IDictionary<K,V>.

It depends on your situation, but it might be enough to construct a real dictionary, and fill it with mock objects.

遗失的美好 2024-10-14 12:13:56

如果不知道您的具体测试场景,我不会模拟 .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.

空城旧梦 2024-10-14 12:13:56

我可以向您保证,字典在 .Net 中工作得很好:)

我认为您在编写测试时需要务实,而不是试图模拟一切。因为你能走多远?你会如何嘲笑 int ?显然,边界线在哪里是可以讨论的,但我通常不会嘲笑:

  • .Net 框架,只要它不连接到某些外部资源
  • 我自己的琐碎类(即仅存储数据的类)
  • 静态辅助方法(这些)不过应该非常简单),包括扩展方法

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:

  • .Net framework as long as it doesn't connect to some external resources
  • my own trivial classes (i.e. ones that only store data)
  • static helper methods (these should be really simple though), including extension methods
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文