在 JUnit (4.8.1) 测试套件中分配 static final int
我有一个 JUnit 测试类,其中有几个 static final int
,可以在测试器代码的顶部重新定义它们,以允许测试值发生一些变化。我的 @BeforeClass 方法中有逻辑,以确保开发人员输入的值不会破坏我的测试。
如果开发人员设置了 boolean useRandomValues = true;
,我希望通过允许在 @BeforeClass 方法中将这些整数设置为(合理的)随机值来进一步改进变化。我可以简单地删除 final
关键字以允许随机值覆盖初始化值,但我有 final
来确保这些值不会无意中更改,正如一些测试一样依赖于这些值的一致性。
我可以在 JUnit 测试类中使用构造函数吗?如果我尝试将 @BeforeClass 放入测试类的构造函数中,并且创建单独的构造函数似乎不允许对这些变量进行赋值(即使我在声明时将它们保留为未赋值),则 Eclipse 会开始在各处添加红色下划线;< /p>
是否有另一种方法可以确保在 @BeforeClass 方法之后更改这些变量的任何尝试都会导致编译时错误?
是否有其他方法可以确保在 @BeforeClass 方法之后我可以在初始化后做一些最终的事情吗?
I have a JUnit test class in which I have several static final int
s that can be redefined at the top of the tester code to allow some variation in the test values. I have logic in my @BeforeClass method to ensure that the developer has entered values that won't break my tests.
I would like to improve variation further by allowing these ints to be set to (sensible) random values in the @BeforeClass method if the developer sets a boolean useRandomValues = true;
. I could simply remove the final
keyword to allow the random values to overwrite the initialisation values, but I have final
there to ensure that these values are not inadvertently changed, as some tests rely on the consistency of these values.
Can I use a constructor in a JUnit test class? Eclipse starts putting red underlines everywhere if I try to make my @BeforeClass into a constructor for the test class, and making a separate constructor doesn't seem to allow assignment to these variables (even if I leave them unassigned at their declaration);
Is there another way to ensure that any attempt to change these variables after the @BeforeClass method will result in a compile-time error?
Can I make something final after it has been initialised?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用静态构造函数来执行此操作:
You can do this with a static constructor:
您可以使用静态初始值设定项:
You can use a static initializer: