仅在测试期间使用特殊构造函数是否有代码味道? [英] Is it a code smell to have a special constructor only used during testing?

查看:77
本文介绍了仅在测试期间使用特殊构造函数是否有代码味道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类 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));

这篇关于仅在测试期间使用特殊构造函数是否有代码味道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆