问题描述
我使用JUnit 4.我看不到在构造函数中初始化或使用由 @Before
注释的专用init函数之间的区别。这是否意味着我不必担心它?
I'm using JUnit 4. I can't see the difference between initializing in the constructor or using a dedicated init function annotated by @Before
. Does this mean that I don't have to worry about it?
有任何情况下 @Before
推荐答案
不,使用构造函数初始化您的JUnit测试夹具在技术上等于使用 @Before
方法(由于JUnit为每个 @Test
创建一个新的测试类实例)。唯一的(内涵的)区别是它打破了 @Before
和 @After
之间的对称性,一些。 IMHO最好遵守约定(使用 @Before
)。
No, using the constructor to initialize your JUnit test fixture is technically equal to using the @Before
method (due to the fact that JUnit creates a new instance of the testing class for each @Test
). The only (connotational) difference is that it breaks the symmetry between @Before
and @After
, which may be confusing for some. IMHO it is better to adhere to conventions (which is using @Before
).
还要注意,在JUnit之前4和注释,有专门的 setUp()
和 tearDown()
方法 - @在
和 @After
注释之前替换这些,但保留基本逻辑。因此,使用注释也使从JUnit 3或更早版本迁移的人更容易生活。
Note also that prior to JUnit 4 and annotations, there were dedicated setUp()
and tearDown()
methods - the @Before
and @After
annotations replace these, but preserve the underlying logic. So using the annotations also makes life easier for someone migrating from JUnit 3 or earlier versions.
这篇关于JUnit:使用构造函数而不是@Before的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!