如何模拟类的内部方法? [英] How to Mock the Internal Method of a class?

查看:45
本文介绍了如何模拟类的内部方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有内部方法的类,我想模拟内部方法.但是我无法模拟它,即它不是在调用模拟函数而是在调用原始函数.有什么办法可以做到这一点?

I have a class which has a internal method and i want to mock the internal method . But i am unable to mock it i.e. it is not calling the mocked function but calling the original function. Is there any way to achieve this ?

实际上,我是Moq的新手.我有许多类和使用Moq进行测试的类方法.许多类是内部的,许多具有内部的方法,许多具有非虚拟的方法.并且不能更改方法和类上的签名.谁能让我知道如何使用Moq测试这种情况.否则请给我建议其他易于学习和使用的测试框架.

Actually i am a novice to the Moq. I have many classes and methods of the classes to test using the Moq. Many classes are internal , many have internal methods, many have not-virtual methods . And can not change the signature on the methods and classes. Can anyone please let me know how to go about testing this scenario using Moq. Or else please suggest me some other testing framework which is easy to learn and easy to work with .

推荐答案

为什么要模拟内部方法?

Why would you want to mock an internal method?

如果您发现需要模拟内部方法,例如回避依赖项或交互,您可能应该考虑重新设计类.

If you find the need to mock an internal method, say to sidestep a dependency or an interaction, you perhaps should consider redesign of the class.

控制反转

Inversion of Control and Dependency Injection are some possible design strategies that can reduce coupling and increase cohesion of your classes and eliminate the need to mock internal methods.

我不认为通过Moq进行非公开嘲笑有明确的途径.

I don't believe there is a clear path to non-public mocking with Moq.

但是,如果绝对必须,您可以使用 TypeMock隔离器来模拟几乎所有内容.

But, if you absolutely must, you can use TypeMock Isolator to mock just about anything.

而且,这样也不会在喧嚣中迷失方向:Thomas链接了一篇很好的文章,内容涉及使用免费的MS Moles嘲笑非公开成员.

Also, just so it doesn't get lost in the din: Thomas linked a good article on using the free MS Moles to mock non-public members.

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆