Best Practice: Initialize JUnit class fields in setUp() or at declaration?

前端 未结 9 1397
走了就别回头了
走了就别回头了 2020-12-07 09:20

Should I initialize class fields at declaration like this?

public class SomeTest extends TestCase
{
    private final List list = new ArrayList();

    publi         


        
9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 09:58

    In JUnit 3, your field initializers will be run once per test method before any tests are run. As long as your field values are small in memory, take little set up time, and do not affect global state, using field initializers is technically fine. However, if those do not hold, you may end up consuming a lot of memory or time setting up your fields before the first test is run, and possibly even running out of memory. For this reason, many developers always set field values in the setUp() method, where it's always safe, even when it's not strictly necessary.

    Note that in JUnit 4, test object initialization happens right before test running, and so using field initializers is safer, and recommended style.

提交回复
热议问题