例如我有一个带有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设置为模拟的工厂。
那有可能吗,我会怎么做?谢谢
答案 0 :(得分:2)
如果您的代码依赖于ElementFactory
,则可以通过MessageProcessor
类的构造函数注入此类的接口。
例如,您创建了一个接口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"执行此操作。