TDD - 如何为具体的工厂逻辑提供具体实施?

时间:2017-12-19 09:00:28

标签: c# tdd solid-principles

例如,我们有一个ShipmentInformationModelFactory,它的目的是填充模型并将其返回。

internal class ShipmentInformationModelFactory
{
    private IGetCarrierServiceFactory getCarrierServiceFactory;

    public ShipmentInformationModelFactory(IGetCarrierServiceFactory getCarrierServiceFactory)
    {
        this.getCarrierServiceFactory = getCarrierServiceFactory;
    }


    internal ShipmentInformation Create(ICarrierTransaction carrierTransaction, CarrierPackage carrierPackage)
    {
        ShipmentInformation shipmentInformation = new ShipmentInformation();

        // Get the Carrier Service Model for the ID of the carrier service against the Package.
        ICarrierServiceModel carrierServiceModel = this.getCarrierServiceFactory.Get(carrierPackage.CarrierServiceId);

        shipmentInformation.ServiceCode = carrierServiceModel.Code;

        return shipmentInformation;
    }
}

然后我们有一个MockGetCarrierServiceFactory,只返回一些存根数据。

    [TestMethod]
    public void CreateShipmentInformation_ShipmentData()
    {
        ShipmentInformationModelFactory shipmentInformationModelFactory = new ShipmentInformationModelFactory(new MockGetCarrierServiceFactory());

        ShipmentInformation shipmentInformation = shipmentInformationModelFactory.Create();
    }

    internal class MockGetCarrierServiceFactory : IGetCarrierServiceFactory
    {
        public ICarrierServiceModel Get(int carrierServiceModelID)
        {
            ICarrierServiceModel carrierServiceModel = Mock.Create<ICarrierServiceModel>();

            Mock.Arrange(() => carrierServiceModel.Code).Returns("TestCarrier");

            Mock.Arrange(() => carrierServiceModel.Description).Returns("TestDescription");

            return carrierServiceModel;
        }
    }

这很好用,我觉得它很好地遵循SOLID原则,如果我错了,请随时纠正我。

我的问题来自此实现的(实时)具体版本。此时应将具体版本的GetCarrierServiceFactory传递给ShipmentInformationModelFactory?

我应该沿着创建默认构造函数并在其中自动填充的路线做下去吗?

实例化ShipmentInformationModelFactory对象的类可以传递它提供给构造函数,但我刚刚在那里创建了一个依赖项。

我觉得我对80%的TDD和SOLID原则有所了解,但在创建这些工厂方面却迷失了。

1 个答案:

答案 0 :(得分:2)

  

实例化ShipmentInformationModelFactory对象的类可以传递它提供给构造函数,但我刚刚在那里创建了一个依赖项。

你必须有依赖。 ShipmentInformationModelFactory取决于IGetCarrierServiceFactory的具体实现。关键是要避免这些依赖变成耦合。

如果你选择默认的构造函数路由,那么你在ShipmentInformationModelFactory内硬编码那个依赖,从而将两者紧密耦合。

因此解决方案是在应用程序启动时提供依赖性。从代码的起点开始,要么使用IoC容器来实现这些依赖关系,要么使用纯DI(即编写自己的映射代码)。

这样,这两个类保持松散耦合,你的测试方法仍然有效,但你也可以在应用程序本身中连接真正的依赖项。

相关问题