我想为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 skip this method or mock it.
}
}
Run Code Online (Sandbox Code Playgroud)
通过继承基类,您可以扩展它.它更多的是让您的代码进入可测试状态,而不是让Moq为您工作.
或者让您不想运行的逻辑成为您可以模拟的虚拟方法的一部分.(比如@Ohad Horesh的回答:)
public virtual void DoSomethingElse();
mock.Setup(abs => abs.Foo()); //here the mocked method will be called
// rather than the real one
Run Code Online (Sandbox Code Playgroud)如果这些选项不可行,那么您将要么必须通过派生类测试该功能,要么使用另一个模拟框架,如TypeMock Isolator,Moles或JustMock.