问题描述
-
@Before
和@BeforeClass
-
@After
和@AfterClass
@Before
and@BeforeClass
@After
and@AfterClass
按照 @Before
中的使用下面的案例:
According to the JUnit Api @Before
is used in the following case:
当编写测试,是很常见的发现,几个测试需要创建才可以运行类似的对象。
而 @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的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!