将 Mock 对象与 Dictionary 一起使用
我刚刚开始使用 NMock 进行单元测试,
我的一个测试用例涉及在字典中添加一个条目,然后将其传递给被测试的单元。我将地图定义为:
var item = new Mock<MyClass>().Object;
var myMap = new Dictionary<MyClass, IList<MyOtherClass>>
{
{ item, completionRequirement }
};
但是,当我在正在测试的单元内执行 myMap.ContainsKey(item)
时,它会返回 false
。
我可以在检查字典时查看代理项目。我猜测我还需要对模拟的 item
执行其他操作。(最有可能定义 .Equals(object o)
)。
我的问题是:
- 如何为模拟的
item
定义 Equals(object o) 。 - 或者是否有完全不同的解决方案?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能还想模拟字典。也就是说,重构为使用
IDictionary
,然后传入模拟字典。然后,您可以设置期望,以便它根据需要返回模拟对象。在这种情况下,您也可能根本不需要使用模拟。从您给我们的内容中无法得知,但我经常发现刚接触模拟的人有时会忘记,如果这些对象没有级联依赖项,您也可以使用真实的对象。例如,您实际上并不需要模拟一个只是简单容器的类。创建一个并使用它。只是需要思考一下。
You might want to mock the dictionary as well. That is, refactor to use
IDictionary<MyClass,IList<MyOtherClass>
, then pass in a mocked dictionary. You can then set up expectations so that it returns mocked objects as necessary.It's also possible that you may not need to use a mock at all in this instance. It's not possible to tell from what you've given us, but I've often found that people new to mocking can sometimes forget that you can use the real objects as well if those objects don't have cascading dependencies. For example, you don't really need to mock a class that's just a simple container. Create one and use it, instead. Just something to think about.
http://richardashworth.blogspot 给出的方法.com/2011/12/using-reflection-to-create-mock-objects.html 采用 Java 语言,但提出了使用反射解决此问题的另一种方法。
The approach given at http://richardashworth.blogspot.com/2011/12/using-reflection-to-create-mock-objects.html is in Java, but presents another approach to this problem using Reflection.
我喜欢按照 tvanfosson 的建议设置一个“假”对象的想法。
但如果您想使用模拟框架来完成此操作,我认为您所需要做的就是设置对 item.Object 应该是什么的期望。在 Rhino Mocks 中,语法类似于:
也就是说,我不知道 NMocks 中的等效代码是什么,但如果您正在使用它,应该不难弄清楚(您可以随时询问关于用户组的问题)。
华泰
I like the idea of setting up a 'fake' object along the lines of what tvanfosson is suggesting.
But if you want to do it with a mocking framework, I think all you need to do is setup an expectation for what item.Object should be. In Rhino Mocks the syntax would be something like:
That said, I have no idea what the equivalent code would be in NMocks, but it shouldn't be hard to figure it out if you're working with it (you can always ask a question on the user group).
HTH