How do I mock a class without an interface?(如何模拟没有接口的类?)
问题描述
我正在使用 Windows 7 中的 C# 开发 .NET 4.0.
I am working on .NET 4.0 using C# in Windows 7.
我想使用 mock 测试一些方法之间的通信.唯一的问题是我想在不实现接口的情况下做到这一点.那可能吗?
I want to test the communication between some methods using mock. The only problem is that I want to do it without implementing an interface. Is that possible?
我刚刚阅读了很多关于模拟对象的主题和一些教程,但它们都用于模拟接口,而不是模拟类.我尝试使用 Rhino 和 Moq 框架.
I just read a lot of topics and some tutorials about mock objects, but all of them used to mock interfaces, and not the classes. I tried to use Rhino and Moq frameworks.
推荐答案
只需将您需要伪造的任何方法标记为 virtual(而不是私有).然后,您将能够创建一个可以覆盖该方法的假货.
Simply mark any method you need to fake as virtual (and not private). Then you will be able to create a fake that can override the method.
如果您使用 new Mock<Type> 并且您没有无参数构造函数,那么您可以将参数作为上述调用的参数传递,因为它采用 param 类型对象
If you use new Mock<Type> and you don't have a parameterless constructor then you can pass the parameters as the arguments of the above call as it takes a type of param Objects
这篇关于如何模拟没有接口的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何模拟没有接口的类?
基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
