问题描述
两者的主要区别是什么
@Before
和@BeforeClass
- 以及在 JUnit 5
@BeforeEach
和@BeforeAll
@Before
and@BeforeClass
- and in JUnit 5
@BeforeEach
and@BeforeAll
根据JUnit Api
@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?推荐答案
标记为
@Before
的代码在每次测试前执行,而@BeforeClass
在整个测试前运行一次测试夹具.如果你的测试类有十个测试,@Before
代码会被执行十次,而@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
.建立数据库连接就属于这一类.您可以将代码从@BeforeClass
移动到@Before
,但您的测试运行可能需要更长的时间.请注意,标记为@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.在 JUnit 5 中,标签
@BeforeEach
和@BeforeAll
是 JUnit 4 中@Before
和@BeforeClass
的等价物.它们的名称更能说明它们何时运行,大致解释如下:在每次测试之前'和'在所有测试之前一次'.In JUnit 5, the tags
@BeforeEach
and@BeforeAll
are the equivalents of@Before
and@BeforeClass
in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.这篇关于@Before、@BeforeClass、@BeforeEach 和 @BeforeAll 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- and in JUnit 5
- 以及在 JUnit 5