仅在测试期间使用特殊构造函数是否有代码味道?

编程入门 行业动态 更新时间:2024-10-12 03:19:41
本文介绍了仅在测试期间使用特殊构造函数是否有代码味道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

仅在测试期间使用特殊构造函数是否有代码味道?

本文发布于:2023-11-24 11:45:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625069.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   味道   代码   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!