如何对创建实例的单元进行测试? [英] How to unit test instance creation?
问题描述
我有一个 Carpenter
类,它使用 Lathe
和 Wood进行工作
对象。
I have a Carpenter
class that does it's work using a Lathe
and a Wood
object.
class Carpenter
{
function Work()
{
$tool = new Lathe();
$material = new Wood();
$tool->Apply($material);
}
}
车床
依赖于称为 Material
的接口,因此我可以通过为其提供伪造的<$来轻松地对 Lathe
进行单元测试。 c $ c>材料在我的单元测试中。 Wood
不依赖任何东西,因此也可以轻松测试。
Lathe
depends on an interface called Material
, so I can easily unit test Lathe
by giving it a fake Material
in my unit test. Wood
doesn't depend on anything, so it can also be easily tested.
interface Material {
// Various methods...
}
interface Tool {
function Apply(Material $m);
}
class Wood implements Material {
// Implementations of Material methods
}
class Lathe {
function Apply(Material $m) {
// Do processing
}
}
但是,木匠
取决于具体类车床
和木
,因为它必须创建它们的实例。这意味着,按照目前的情况,如果不经意引入 Lathe
和<$就不能对 Work()
方法进行单元测试c $ c> Wood 进行测试。
However, Carpenter
depends on the concrete classes Lathe
and Wood
because it has to create instances of them. That means that as it currently stands, I cannot unit test the Work()
method without inadvertantly bringing Lathe
and Wood
under test.
我应该如何将设计更改为单元测试 Carpenter
?
How should I change my design to unit test Carpenter
?
推荐答案
您可以在以下两个不同的方向进行操作:
There's a couple of different directions you can take here:
- 使用构造函数注入,只需将工具和材质实例注入木匠即可。
- 如果由于某些原因无法注入实例(也许是因为您需要为每次调用Work方法创建新实例),则可以注入 Abstract Factories 。
- 您还可以使用ctford描述的 Factory方法方法,但这需要您还创建特定于测试的替代值以进行单元测试,但这是完全有效的做法要做的只是更多的工作,在许多情况下,其他选择会更好,更灵活。
- Use Constructor Injection and simply inject the tool and the material instances into the carpenter.
- If injecting instances doesn't work for some reason (perhaps because you need to create new instances for every invocation of the Work method), you can inject Abstract Factories instead.
- You can also use the Factory Method approach described by ctford, but that requires you to also create test-specific overrides to be able to unit test, and while that's a completely valid thing to do, it's just more work and in many cases the other alternatives are better and more flexible.
这篇关于如何对创建实例的单元进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!