假设我有一个类 Foo ,该类仅使用类 Bar 的实例进行实例化:
Assume I have a class Foo which is only instantiated with an instance of class Bar:
public Foo(Bar x) { this.a = x.a(); this.b = x.b(); ... }现在我想测试 Foo ,并进一步假设很难创建具有所需状态的 Bar 实例。另外一个约束是,将 a,b,... 字段声明为final,因此该字段的设置器不可用。
Now I would like to test Foo, further assuming an instance of Bar with the desired state is difficult to create. As an additional constraint, the fields a, b, ... are declared as final, so setters for this fields are not available.
一种可能是在Foo中创建一个附加的构造函数:
A possibility would be to create an additional constructor in Foo:
protected Foo(A a, B b, ...) { this.a = a; this.b = a; ... }此构造函数仅在测试期间使用,我会在此构造函数的注释中声明。
This constructor is only used during testing, which I would declare in the comment for this constructor.
问题:这是代码气味吗?
Question: Is this a code smell?
我想到的另一种解决方案是嘲笑 Bar 。
Another solution I was thinking of was mocking Bar. Wonder if its the best practice in this case?
推荐答案模拟酒吧更有可能被视为最佳实践。您应该能够创建一个MockBar,这样就可以
Mocking Bar is more likely to be considered best practice. You should be able to create a MockBar so you can do
Foo foo = new Foo(new MockBar(a, b));更多推荐
仅在测试期间使用特殊构造函数是否有代码味道?
发布评论