[英]Using NSubstitute is it possible to mock/stub a base class virtual method?
[英]Is it possible to mock a local method variable using NSubstitute?
例如,我有一个带有 Process 方法的 class,在这个方法中我设置了一些东西,例如
public class messageProcessor
{
...
public string Process(string settings)
{
var elementFactory = new ElementFactory();
var strategyToUse = new legacyStrategy();
...
var resources = new messageResource(
elementFactory,
strategyToUse,
...);
}
}
我是否可以创建此 class 的实例,但是当我调用 Process 方法时,替换(例如)elementFactory 以设置为我的模拟工厂。
这可能吗?我该怎么做? 谢谢
如果你的代码依赖于ElementFactory
,你可以通过MessageProcessor
class 的构造函数注入这个 class 的接口。
这称为“控制反转” 。
例如,您创建了一个接口IElementFactory
,您可以通过如下构造函数将其注入 class 中:
public class messageProcessor
{
private readonly IElementFactory elementFactory;
public messageProcessor(IElementFactory elementFactory)
{
this.elementFactory = elementFactory;
}
public string Process(string settings)
{
var strategyToUse = new legacyStrategy();
...
var resources = new messageResource(
this.elementFactory,
strategyToUse,
...);
}
}
现在,在您的测试中,您可以注入IElementFactory
的替代品。 像这样:
public void Test()
{
var elementFactory = Substitute.For<IElementFactory>();
// tell the substitute what it should return when a specific method is called.
elementFactory.AnyMethod().Returns(something);
var processor = new messageProcessor(elementFactory);
}
在运行时,您的应用程序应将IElementFactory
的实例注入到messageProcessor
class 中。 您应该通过“依赖注入”来执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.