通过接口创建假对象
我需要通过接口动态创建假对象。这个假对象的每个方法和属性都应该抛出 NotImplementedException。有没有简单的方法可以仅使用 .NET 反射 API 来做到这一点?
I need to dynamically create fake object by interface. Every method and property of this fake object should just throw NotImplementedException. Is there any simple way how to do it only with .NET reflection API?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用模拟 API,例如 Moq。它是为单元测试中的模拟而设计的,但它应该可以满足您的需要。
You could use a mocking API such as Moq. It's designed for mocking in unit tests, but it should do what you need.
也许 ImpromptuInterface 可以提供帮助。
示例代码(从其主页复制)是:
Maybe ImpromptuInterface can help.
A sample code (copied from its homepage) is:
Castle Proxies 是一个简洁的库,可以在运行时为接口生成代理对象。所有主要的模拟框架也在底层使用 Castle Proxies。
学习曲线比使用 Moq 之类的东西更陡峭,但它可能更适合您的需求,因为 Moq 被设计为专门用于单元测试,因此 API 对于您所追求的东西来说可能太“嘈杂”。
Castle Proxies is a neat library that generates proxy objects for interfaces at run time. All the major mocking frameworks use Castle Proxies under the hood too.
The learning curve is steeper than using something like Moq, but it may be a more appropriate fit for your needs as Moq is designed to be used specifically for unit testing so the API may be too 'noisy' for what you're after.
恐怕您唯一的解决方案是使用 Reflection.Emit,这不是很简单:)
请参阅 C# 反射:向现有程序集发出类 或 反射发射 了解更多信息。
I'm afraid that your only solution is to use Reflection.Emit, and that is not very simple :)
See C# Reflection: Emitting classes to existing assemblies or Reflection Emit for some more info.