简体   繁体   English

JUnit如何仅在测试类内部定义一次的情况下管理运行@BeforeClass

[英]How JUnit manages running @BeforeClass only once which is defined inside the test class

I very much understand what @BeforeClass is. 我非常了解@BeforeClass是什么。 It is executed once before JUnit test run is started & @Before method is executed before every test case. 它在开始JUnit测试运行之前执行一次,并且在每个测试用例之前执行@Before方法。 My question is regarding a very old post by a very senior stackoverflow user (Péter Török 68.8k) Please refer [stackoverflow question] [1]: JUnit: using constructor instead of @Before which was posted about 2 yrs ago but on JUnit4. 我的问题是关于一个非常资深的stackoverflow用户(PéterTörök68.8k)的一篇很老的帖子,请参考[stackoverflow问题] [1]: JUnit:使用构造函数而不是大约2年之前发布在JUnit4上的@Before。 so I think it is still valid and true. 所以我认为它仍然是正确的。

Here he mentions 他在这里提到

@Before is equivalent to constructor of test class @Before等效于测试类的构造函数

and

JUnit creates a new instance of the test class for each @Test, JUnit为每个@Test创建测试类的新实例,

So how does JUnit manage running @BeforeClass only once which is defined inside the test class? 那么,JUnit如何仅管理一次在测试类中定义的@BeforeClass运行?

Methods annotated with @BeforeClass must be static. @BeforeClass注释的方法必须是静态的。 JUnit doesn't need any instance of the test class to call it. JUnit不需要测试类的任何实例来调用它。

Well, jUnit could run the method annotated with @BeforeClass at time of class loading, that is like you would implement on your own with a static initializer. 好吧,jUnit可以在加载类时运行@BeforeClass注释的方法,就像您将使用静态初始化程序自己实现一样。

You get also the hint that jUnit is doing something like this by the fact that @BeforeClass and @AfterClass annotated methods must be static. 通过@BeforeClass@AfterClass注释的方法必须是静态的事实,您还会得到jUnit正在执行类似操作的提示。

That's because @BeforeClass has to be a static method. 这是因为@BeforeClass必须是静态方法。 Once it is static, JUnit knows how to run it once. 一旦是静态的,JUnit就会知道如何运行一次。

Sometimes several tests need to share computationally expensive setup (like logging into a database). 有时,一些测试需要共享计算量大的设置(例如登录数据库)。 While this can compromise the independence of tests, sometimes it is a necessary optimization. 尽管这可能会损害测试的独立性,但有时这是必要的优化。 Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. @BeforeClass注释一个public static void no-arg方法会导致它在类中的任何测试方法之前运行一次。 The @BeforeClass methods of superclasses will be run before those the current class. 超类的@BeforeClass方法将在当前类之前运行。 Static methods are not belongs to instances of the class. 静态方法不属于该类的实例。 Those are properties of the class. 这些是该类的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM