有没有办法复制 Moq Mock<>按价值?
我在 System.Data.DataSet 前面使用接口(IDataSet)用于测试目的。我希望能够模拟 Copy() 方法。基本上我想要同一个模拟对象的副本/克隆。
这是我想做的一些伪代码。
Mock<IDataSet> dataMock = new Mock<IDataSet>();
Mock<IDataSet> copyMock = ??? // How do I clone the mock?
dataMock.Setup(c => c.Copy()).Returns(copyMock.Object);
这可能吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本上,Mock 不是真实的东西,因此它没有真正的行为。它不应该有真正的行为——它应该做你告诉它的任何事情,同时跟踪发生的事情。不多也不少。
这意味着您必须告诉它其 Copy 方法如何工作。如果您执行以下操作,这就是 Copy 方法将具有的实现:
但是,您也可以执行以下操作:
然后,that 就成为 Copy 方法的实现。请记住:接口不是一个规定方法应该做什么的契约;而是一个契约。它仅定义方法的签名。
您可能希望将数据从一个 IDataSet 复制到另一个 IDataSet,但请记住 Mock 是纯粹的行为;它没有数据。
您可以考虑以下几种替代方案:
您可以在优秀书籍 xUnit 中阅读有关 Stubs、Mocks、Fakes 和其他单元测试设计模式的内容测试模式。
Basically, a Mock is not the real thing, so it does not have real behavior. It's not supposed to have real behavior - it's supposed to do whatever you tell it while keeping track of what happened. Nothing more and nothing less.
This means that you have to tell it how its Copy method works. If you do the following, that's the implmementation the Copy method will have:
However, you can also do this:
and that, then, becomes the implementation of the Copy method. Remember: an interface is not a contract that states what the method should do; it only defines the signature of methods.
You were probably hoping to copy data from one IDataSet to another, but remember that a Mock is pure behavior; it has no data.
A couple of alternatives you can think about are the following:
You can read about Stubs, Mocks, Fakes and other unit testing design patterns in the excellent book xUnit Test Patterns.