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

前端 未结 9 1399
走了就别回头了
走了就别回头了 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 10:14

    Since each test is executed independently, with a fresh instance of the object, there's not much point to the Test object having any internal state except that shared between setUp() and an individual test and tearDown(). This is one reason (in addition to the reasons others gave) that it's good to use the setUp() method.

    Note: It's a bad idea for a JUnit test object to maintain static state! If you make use of static variable in your tests for anything other than tracking or diagnostic purposes, you are invalidating part of the purpose of JUnit, which is that the tests can (an may) be run in any order, each test running with a fresh, clean state.

    The advantages to using setUp() is that you don't have to cut-and-paste initialization code in every test method and that you don't have test setup code in the constructor. In your case, there is little difference. Just creating an empty list can be done safely as you show it or in the constructor as it's a trivial initialization. However, as you and others have pointed out, anything that can possibly throw an Exception should be done in setUp() so you get the diagnostic stack dump if it fails.

    In your case, where you are just creating an empty list, I would do the same way you are suggesting: Assign the new list at the point of declaration. Especially because this way you have the option of marking it final if this makes sense for your test class.

提交回复
热议问题