使用NSubstitute是否可以模拟/存根基类虚拟方法



我有一个继承层次结构,看起来像这样;

public abstract class SomeBaseClass
{
public virtual void DoSomething()
{
Console.WriteLine("Don't want this to run");
}
}
public class ConcreteImplementation1 : SomeBaseClass
{
}
public class ConcreteImplementation2 : ConcreteImplementation1
{
public override void DoSomething()
{
Console.WriteLine("This should run");
base.DoSomething();
}
}

使用NSubstitute,我想截断ConcreteImplementation1的DoSomething((,这样只有ConcreteIamplementation2的DoSomehing(((方法中的代码才能与对base的调用一起运行。DoSomething((什么也不做。

这可能吗?如果可能,我该怎么做?如果DoSomething((是异步的,代码看起来会有什么不同吗?

感谢

我认为NSubstitute或一般的.NET都不可能做到这一点。NSubstitute确实支持部分mock,但这是基于每个成员的。

因此,您可以让它调用ConcreteImplementation2.DoSomething,但该实现调用base.DoSomething,以便执行:

var sub = Substitute.For<ConcreteImplementation2>();
sub.When(x => x.DoSomething()).CallBase();

NSubstitute通过实现/子类化一个类型来工作,所以一个很好的经验法则是,如果你不能通过子类化手动完成某件事,NSsubstitute也将无法完成。

在这种情况下,如果创建一个class ConcreteImplementation3 : ConcreteImplementation2并覆盖DoSomething,是否可以在不调用SomeBaseClass.DoSomething的情况下调用ConcreteImplementation2.DoSomething?在这种情况下,我认为答案是否定的,所以NSubstitute也无法做到这一点。

最新更新