我有一个抽象类:
public abstract class MyClass
{
protected abstract bool IsSavable();
protected bool IsExecutable()
{
//New mode or edit mode
if (ViewMode == ViewMode.New || ViewMode == ViewMode.Edit)
{
return IsSavable();
}
//Search mode
if (ViewMode == ViewMode.Search)
{
return true;
}
return false;
}
}
我想对这个类进行单元测试。因此我需要模拟“IsSavable”方法。它应该始终返回“true”。
我知道如何使用 Moq 模拟我的抽象类。但是我如何模拟我的抽象 protected 方法以使其返回 true?
函数 IsSavable 在我的抽象类中通过具体方法 (IsExecuteable) 调用。我想测试这个方法。我知道你们中的大多数人会建议在实现“IsSavable”的类中进行测试。不幸的是,这将有很多类,我只想测试我的方法 IsExecutable 一次。
最佳答案
I would like to unit test this class. Therefor I need to mock the "IsSavable" method. It should always return "true".
不,这是不合逻辑的。您可以创建一个子类来执行您想要的操作:
// Within your test code
class MyClassForTest : MyClass
{
// TODO: Consider making this a property
protected override bool IsSavable()
{
return true;
}
}
然后,当您想要运行测试时,创建一个 MyClassForTest
的实例,而不仅仅是 MyClass
。
就我个人而言,我更喜欢为依赖项 使用模拟框架,而不是我正在测试的类。
关于c# - 模拟抽象保护方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27173941/