如何使用MOQ框架为抽象基类创建Mock? [英] How to create Mock for the abstract base class using MOQ framework?

查看:138
本文介绍了如何使用MOQ框架为抽象基类创建Mock?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为MyClass编写单元测试,但是它的基类是抽象类.

I want to write unit tests for MyClass but its base class is an abstract class.

public class MyClass : AbstractBaseClass
{
}

我想模拟AbstractBase类,以便在创建要测试的MyClass实例时可以跳过其构造函数中的某些逻辑.反正我能做到吗?

I want to Mock the AbstractBase class, so that I can skip some of the logic in its constructor when I create the MyClass instance I want to test. Is there anyway I can do this?

//Unit Test
var test = new Mock<IInterface>();
var derivedclass = new DerivedClass(test.Object);

test.Setup(d=>d.MyMethod(It.IsAny<string>()).returns(2);
derivedclass.MyMethod("hello");


// Derived Class
class DerivedClass : AbstractClass{

     //constuctor
    public DerivedClass(IInterface interface){
        _interface = interface;
    }
    public MyMethod(string str){
        return 2;
    }
}

//Abstract Class
public abstract class AbstractClass
{

 // This method gets called when i create the  instance of the derived class in my unit   
  test..

   protected AbstractedClass() : this(new SomeOtherClass()){
       DoSomethingElse();    /// I want to skip this method or mock it.
   }
 }

推荐答案

通过从基类继承,您可以扩展它.这更多的是让代码进入可测试状态,而不是让Moq为您工作.

By inheriting from the base class you are extending it. It is more about getting your code into a testable state rather than having Moq work for you.

  1. 您可以使用组合代替基类,然后使用可以模拟的依赖项注入(通过接口).
  2. 或者如果您必须继承,则将不想运行的逻辑提取到通过依赖项注入再次注入的另一个类中.
  3. 或者让您不想运行的逻辑成为您可以模拟的虚拟方法的一部分. (就像@Ohad Horesh的回答:)

  1. You can either use composition instead of a base class and then use dependency injection (via an interface) that you can mock.
  2. Or if you have to inherit then extract the logic that you don't want to run into another class that you inject again via dependency injection.
  3. Or have that logic that you don't want to run be part of a virtual method that you can mock. (like @Ohad Horesh's answer:)

public virtual void DoSomethingElse();

mock.Setup(abs => abs.Foo());  //here the mocked method will be called  
                               // rather than the real one

如果这些选项不可行,那么您要么必须通过派生类测试该功能,要么使用其他模拟框架,例如TypeMock Isolator,Moles或JustMock.

If these options are not viable then you will either have to test that functionality through the derived class or use another mocking framework such as TypeMock Isolator, Moles or JustMock.

这篇关于如何使用MOQ框架为抽象基类创建Mock?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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