@Before和@BeforeClass的区别 [英] Difference between @Before and @BeforeClass

查看:1085
本文介绍了@Before和@BeforeClass的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • @Before @BeforeClass

  • @After @AfterClass

  • @Before and @BeforeClass
  • @After and @AfterClass

按照 JUnit的阿比 @Before 中的使用下面的案例:

According to the JUnit Api @Before is used in the following case:

当编写测试,是很常见的发现,几个测试需要创建才可以运行类似的对象。

When writing tests, it is common to find that several tests need similar objects created before they can run.

@BeforeClass 可用于建立数据库连接。但不能 @Before 做?

Whereas @BeforeClass can be used to establish a database connection. But couldn't @Before do the same?

推荐答案

在code标记 @Before 每次测试之前执行,而 @BeforeClass 整个测试夹具之前运行一次。如果您的测试类有十个测试, @Before code会被执行十次,但 @BeforeClass 将只执行一次。

The code marked @Before is executed before each test, while @BeforeClass runs once before the entire test fixture. If your test class has ten tests, @Before code will be executed ten times, but @BeforeClass will be executed only once.

在一般情况下,使用 @BeforeClass 当多个测试需要共享相同的计算昂贵的设置code。建立数据库连接就属于这一类。您可以从移动 @BeforeClass code到 @Before ,但你的测试运行可能需要更长的时间。请注意,code标记 @BeforeClass 运行为静态初始化,所以它会在测试夹具的类实例被创建之前运行。

In general, you use @BeforeClass when multiple tests need to share the same computationally expensive setup code. Establishing a database connection falls into this category. You can move code from @BeforeClass into @Before, but your test run may take longer. Note that the code marked @BeforeClass is run as static initializer, therefore it will run before the class instance of your test fixture is created.

这篇关于@Before和@BeforeClass的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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