如何在Spring中为Delphi使用带有自动接线的模拟?

时间:2013-02-07 16:51:24

标签: delphi dependency-injection mocking ioc-container spring4d

如果我有这些接口:

ISequencer = interface;
IController = interface;

它们的实现(Controller需要通过构造函数注入来执行Sequencer):

TSequencer = class(TInterfacedObject, ISequencer)
end;

TController = class(TInterfacedObject, IController)
  constructor Create(Sequencer: ISequencer);
end;

我在全局容器中注册实现:

GlobalContainer.RegisterType<TSequencer>.Implements<ISequencer>;
GlobalContainer.RegisterType<TController>.Implements<IController>;

GlobalContainer.Build;

最后,通过自动布线功能,我可以获得IController接口的新实例:

Controller := ServiceLocator.GetService<IController>;

对于真正的应用程序代码来说还可以。但是在测试项目中我想模仿ISequencer。根据测试,当我向容器询问ISequencer的实现时,有时我需要真正的实现(TSequencer),有时我需要模拟实现(如TSequencerMock)。我该如何切换?

1 个答案:

答案 0 :(得分:4)

您可以为给定的接口注册多个实现。然后按名称调用它们:

GlobalContainer.RegisterType<TSequencer>.Implements<ISequencer>('real');
GlobalContainer.RegisterType<TController>.Implements<IController>('mock');

然后您可以根据需要按名称调用它们:

Controller := ServiceLocator.GetService<IController>('mock');

我在这里写了一篇关于如何做到的文章:

http://www.nickhodges.com/post/Getting-Giddy-with-Dependency-Injection-and-Delphi-Spring-9-%E2%80%93-One-Interface-Many-Implementations.aspx