JUnit:使用构造函数而不是 @Before [英] JUnit: using constructor instead of @Before

查看:29
本文介绍了JUnit:使用构造函数而不是 @Before的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 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 在构造函数中提供的不仅仅是初始化,是否有任何情况?

Is there any case when @Before gives more than just initializing in the constructor?

推荐答案

不,使用构造函数初始化 JUnit 测试装置在技术上等同于使用 @Before 方法(因为JUnit 为每个 @Test 创建一个测试类的新实例.唯一的(内涵上的)区别是它打破了 @Before@After 之间的对称性,这可能会让一些人感到困惑.恕我直言,最好遵守约定(使用 @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() 方法 - @Before@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.

来自评论的更多详细信息:

More details from comments:

  • @Before 允许覆盖父类行为,构造函数强制你调用父类构造函数
  • 构造函数在之前子类构造函数和@Rule方法运行,@Before在所有这些之后运行
  • @Before 期间的异常导致 @After 方法被调用,构造函数中的异常不会
  • @Before allows overriding parent class behavior, constructors force you to call parent class constructors
  • The constructor runs before subclass constructors and @Rule methods, @Before runs after all of those
  • Exceptions during @Before cause @After methods to be called, Exceptions in constructor don't

这篇关于JUnit:使用构造函数而不是 @Before的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆