相关疑难解决方法(0)

如何使用MOQ框架为抽象基类创建Mock?

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

public class MyClass : AbstractBaseClass
{
}
Run Code Online (Sandbox Code Playgroud)

我想模拟AbstractBase类,这样当我创建我想要测试的MyClass实例时,我可以跳过其构造函数中的一些逻辑.无论如何我能做到吗?

//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 …
Run Code Online (Sandbox Code Playgroud)

unit-testing moq

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

moq ×1

unit-testing ×1