简体   繁体   English

如何使用 MOQ 模拟基类函数调用?

[英]How do I mock base class function calls using MOQ?

In the below given scenario, I have added reference to someExternal.Library.dll and derived a class named MyClass from BaseClass .在下面给出的场景中,我添加了对 someExternal.Library.dll 的引用,并从BaseClass派生了一个名为MyClass的类。 MyClass invokes MakeCall() method of BaseClass internally in its methods. MyClass在其方法中内部调用BaseClass MakeCall()方法。 Here, the BaseClass is a concrete class which does not implement any Interface and also the MakeCall() method is a non-virtual method.在这里, BaseClass是一个具体的类,它没有实现任何接口,而且MakeCall()方法是一个非虚拟方法。

in such a scenario, how do I mock only the MakeCall() method of base class?在这种情况下,我如何只模拟基类的MakeCall()方法? I want to write unit tests for MyClass我想为MyClass编写单元测试

public class MyClass : BaseClass
{

public void DoSomething()
{
    //someExternal.Library.dll is referenced to the project
    // Makecall() is available to this class through inheritance 

    MakeCall();
    ...

}

    public bool DoSomethingElse()
{
        ...
    }
}

in the above snippet I want to write unit Test for MyClass and I should be able to Mock obj.MakeCall();在上面的代码片段中,我想为MyClass编写单元测试,我应该能够模拟obj.MakeCall(); method call using MoQ.使用 MoQ 的方法调用。

NOTE: MOQ is the only mocking framework I am allowed to use注意:MOQ 是我唯一可以使用的模拟框架

Since your base method neither implements any interface nor marked as virtual, Moq can't help you at that specific scenario, since it generates a proxy that will implement the interface or create a derived class that overrides a method in order to intercept calls.由于您的基本方法既没有实现任何接口也没有标记为虚拟,因此 Moq 无法在该特定场景中为您提供帮助,因为它会生成一个代理来实现该接口或创建一个派生类来覆盖某个方法以拦截调用。

If your base class is not a legacy code you can't touch by any means, I would recommend to add an interface and mock it directly.如果您的基类不是您无法通过任何方式触及的遗留代码,我建议您添加一个接口并直接模拟它。

Otherwise, see the following answer for Moq alternatives that work directly with the IL and can mock sealed classes:否则,请参阅以下有关直接与 IL 一起使用并可以模拟密封类的 Moq 替代方案的答案:

https://stackoverflow.com/a/21793891/3400897 https://stackoverflow.com/a/21793891/3400897

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM