Junit 中是否有任何理由不在声明时创建对象?

发布于 2024-09-08 19:59:57 字数 259 浏览 2 评论 0原文

是否有任何理由将对象创建放在 setUp() 内部而不是在实例变量声明中?

我在书中看到过这样做,但效果是相同的,我不确定这样做是否出于最佳实践的原因,因为早期版本的 Junit 没有为每个测试实例化对象(请参阅此处),或者如果这只是一种风格。

Is there any reason to put object creation inside of setUp() rather than at an instance variable declaration?

I've seen it done this way in books, but the effect is the same and I'm not sure if it was done for a best practice reason, because an earlier version of Junit did not instantiate the object for each test (see here), or if it's just a style thing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

左秋 2024-09-15 19:59:57

如果所讨论的对象的实例化不依赖于外部因素,那么立即声明和定义它是完全可以的。然而,它通常取决于其他因素(例如单例*的初始化),或者需要构造函数参数 - 其中一些甚至可能依赖于测试 - 或者它的初始化需要多个步骤。然后,您必须将实例化推迟到设置方法,甚至推迟到测试方法本身。

请注意,JUnit 会创建测试类的新实例,因此无论如何都会为每个测试方法执行创建其数据成员的新实例。因此,如果您没有上述任何依赖项,那么从语义上讲,在声明点或在设置方法中实例化成员没有区别。

*这是单身人士不受欢迎的原因之一。但是,通常您仍然拥有它们,尤其是在遗留代码中。

If the instantiation of the object in question does not depend on external factors, it is perfectly OK to declare and define it at once. However, often it depends on other factors (e.g. initialization of a singleton*), or requires constructor parameters - some of which may even be test-dependent -, or its initialization takes multiple steps. Then you have to defer instantiation to the setup method, or even to the test method itself.

Note that JUnit creates a new instance of the test class, thus a new instance of its data members for each test method execution anyway. So if you have none of the dependencies mentioned above, semantically there is no difference between instantiating a member at the point of declaration or in the setup method.

*this is one of the reasons Singletons are not liked. However, often you still have them, especially in legacy code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文