gpt4 book ai didi

java - JUnit - 静态类是否维护测试类之间的状态?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:14:09 26 4
gpt4 key购买 nike

我有一个单元测试类,单独运行时通过。当我将它与包中的所有其他测试一起运行时,它失败了,因为一个独立的静态类没有被初始化。这个独立的静态类被其他类使用,因此它的状态似乎在测试之间保持不变。

我的观察是正确的还是发生了其他事情?另外,如果有人可以提供链接或其他内容作为引用,那就太好了。

谢谢!

最佳答案

This independent static class is used by other classes and so it seems that its state is maintained between tests.

是的。那就是将要发生的事情。这只是静力学尴尬的原因之一。

静态字段在定义它们的类的生命周期内存在,这通常意味着 JVM 的生命周期。我试图在 JLS 中找到明确说明这一点的地方。我能找到的最接近的是 JLS 8.3.1.1其中说:

"If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4)."

JLS 在其他地方说一个类只初始化一次。

异常(exception)情况是类被卸载时,但这里不会发生这种情况。或者至少,不是正常/默认的 JUnit 框架行为。 (但可以做到:参见 Using different classloaders for different JUnit tests? )

如果您担心的话,没有任何 JUnit“魔法”可以将静态变量重置为初始状态(无论您如何定义)。考虑实现它太复杂(也太可怕)。

关于java - JUnit - 静态类是否维护测试类之间的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22677467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com