我想为 MyClass 编写单元测试,但它的基类是一个抽象类。
public class MyClass : AbstractBaseClass
{
}
我想模拟抽象基类,以便在创建要测试的 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.
}
}
通过从基类继承,您可以扩展它。它更多的是让您的代码进入可测试状态,而不是让 Moq 为您工作。
- 您可以使用组合而不是基类,然后使用可以模拟的依赖项注入(通过接口)。
- 或者,如果您必须继承,则提取您不想运行的逻辑到您通过依赖注入再次注入的另一个类中。
-
或者将您不想运行的逻辑作为您可以模拟的虚拟方法的一部分。 (就像@Ohad Horesh 的回答:)
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。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)