简体   繁体   English

依赖注入仅用于测试吗?

[英]Dependency injection is only for testing?

I read many times that hardcoding object is not a good practice: 我读过很多遍,硬编码对象不是一个好习惯:

class Session
{
    private $user;

    function __construct()
    {
        $this->user = new User();
    }
}

its bad only because of its untestable behaviour? 它的坏处仅是因为其无法测试的行为? I simply find this hardcoding easier to read. 我只是觉得这种硬编码更容易阅读。 Of course I can add those methods to be DI-like: 当然,我可以将这些方法添加为类似于DI的方法:

    public function setUser (User $userObj)
    {
        $this->user = $userObj;
    }

    public function getUser()
    {
        return $this->user;
    }

But then its like a house where even the trussing can be changed. 但是,它就像一间甚至可以更改桁架的房屋。 What for? 做什么的?

Unlike a house, which is a physical object and where the trussing can't be changed, this is code, wherein things are less permanent. 与房屋不同,房屋是一个物理对象,并且无法更改其桁架,这与代码不同,因为代码的永久性较低。

To be honest, having used DI for years I think it's overused. 老实说,使用DI多年,我认为它已经被滥用。 Quite simply: a bunch of a class's dependencies won't change, and if they do,it's easy enough to then apply DI to them. 很简单:一帮一类的依赖不会改变,如果他们这样做,这是很容易申请DI给他们。

Sticking with the house analogy, my position is becoming "don't necessarily build the entire house extension now, but also don't build a load-bearing wall where a door might need to go". 坚持房屋类比,我的立场是“现在不必建造整个房屋,也不必在可能需要开门的地方建造承重墙”。 I'd create your dependency objects in your constructor, so if it ever becomes necessary to make them swapabble, it's easy enough to add a constructor arg and start passing the dependency in via a DI framework if needs must. 我会在构造函数中创建依赖对象,因此,如果有必要使它们互换,添加构造函数arg并在需要时通过DI框架开始传递依赖关系就足够了。

One thing you're leaving yourself open for then is that every instance where that class is created will then need to be replaced with a DI-friendly version, which means a lot of refactoring, and accordingly a lot of regression testing. 那时,您要放开自己的一件事是,然后将用DI友好版本替换创建该类的每个实例,这意味着需要大量重构,并因此需要进行大量回归测试。 This is a heavy risk. 这是很大的风险。 If you make sure you've got very thorough automated test coverage, a lot of this risk is mitigated. 如果您确定自己拥有非常全面的自动化测试范围,则可以减轻很多此类风险。

On the other hand... using a DI framework from the outset, even if the dependencies aren't injected immediately, it'll still mitigate this consideration even more, when it comes time to need to inject them. 另一方面...从一开始就使用DI框架,即使没有立即注入依赖项,当需要注入它们时,它仍将进一步减轻这种考虑。

Using DI certainly does make your testing a lot easier, which in turn will increase your ability to achieve higher test coverage. 使用DI确实可以使您的测试容易得多,这反过来又会提高您实现更高测试覆盖率的能力。 But I also don't think one should code specifically for testing. 但是我也不认为应该专门为测试编写代码。

So there's a few things to weigh-up and apply to your specific style and requirements when making this decision. 因此,在做出此决定时,需要权衡一些因素并将其应用于您的特定样式和要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM