是否可以使用NSubstitute模拟本地方法变量?

时间:2019-10-29 11:31:23

标签: c# unit-testing testing nsubstitute

例如我有一个带有Process方法的类,在这种方法中,我设置了很多东西,例如

public class messageProcessor
{
...
  public string Process(string settings)
  {
    var elementFactory = new ElementFactory();
    var strategyToUse = new legacyStrategy();
    ...
    var resources = new messageResource(
       elementFactory,
       strategyToUse,
       ...);
  }
}

是否可以创建此类的实例,但是当我调用Process方法时,替换(例如)elementFactory设置为模拟的工厂。

那有可能吗,我会怎么做?谢谢

1 个答案:

答案 0 :(得分:2)

如果您的代码依赖于ElementFactory,则可以通过MessageProcessor类的构造函数注入此类的接口。

这称为"Inversion of control"

例如,您创建了一个接口IElementFactory,您可以通过以下构造函数将其注入到类中:

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类中。您应该通过"Dependency injection"执行此操作。

相关问题