单元测试时如何重新初始化静态finals [英] How to reinitialize static finals while unit testing
问题描述
我正在为一个具有静态最终变量的类编写单元测试.然而,由于静态最终变量的状态在每次测试中都被修改,我需要一些方法来重新初始化它.
这怎么可能?我需要使用某种自定义类加载器吗?
变量初始化为 -<前>静态最终 CountdownLatch 锁存器 = 新 CountdownLatch(1);
当然你可以通过反射或类加载来解决它,但是如果我是你,我就不会从这里开始."可变静态是非常邪恶的(即使是那些被称为单例的).因此,通过从上面进行参数化"来更好地设计您的代码 - 将对象传递给需要它们的人,而不是做一些硬连接或使用目录服务.
I am writing unit tests for a class, which has a static final variable. However, since the state of the static final var is modified in each test, I need some way to reinitialize it.
How would this be possible? Would i need to use some sort of a custom classloader?
The variable is initialized as -
static final CountdownLatch latch = new CountdownLatch(1);
Of course you can hack around it with reflection or class loading, but "if I were you, I wouldn't be starting form here." Mutable statics are really evil (even those called singletons). So, design you code better by "parameterisation from above" - pass object into those that need them, rather than doing something hardwired or using a directory service.
这篇关于单元测试时如何重新初始化静态finals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!