我通过构造函数注入使用 IoC 容器而不是 DI。有些人可能会问为什么我使用 IoC 容器而不是构造函数注入。出于此处所述的原因:为什么我需要一个 IoC 容器而不是简单的 DI 代码?. 但是,我发现为我的服务创建单元测试很困难。我不确定如何在运行时模拟我的服务使用的存储库,因为我没有使用构造函数注入(一个难题)。任何人有任何解决方案?
例如:
public class SomeService
{
private ISomeServiceRepository someServiceRepository;
public GetSomeThing()
{
//how do I mock this repository in my unit test
someServiceRepository = IoC.Resolve<ISomeServiceRepository>();
someData = someServiceRepository.getData();
someOtherService = new SomeOtherService();
someThing = someOtherService.GetSomeThing();
return FigureOutSomeThingElse(someData, someThing);
}
public FigureOutSomeThingElse(someData, someThing)
{
//do some figuring
return somethingElse;
}
}
public class SomeOtherService
{
private ISomeServiceRepository someOtherServiceRepository;
public GetSomeThing()
{
//how do I mock this repository in my unit test
someOtherServiceRepository = IoC.Resolve<ISomeOtherServiceRepository>();
var someData = someOtherServiceRepository.getData();
return someData;
}
}