JUnit: using constructor instead of @Before

前端 未结 8 812
旧巷少年郎
旧巷少年郎 2020-12-04 14:10

I\'m using JUnit 4. I can\'t see the difference between initializing in the constructor or using a dedicated init function annotated by @Before. Does this mean

8条回答
  •  死守一世寂寞
    2020-12-04 14:46

    Quote from http://etutorials.org/Programming/Java+extreme+programming/Chapter+4.+JUnit/4.6+Set+Up+and+Tear+Down/

    You may be wondering why you should write a setUp( ) method instead of simply initializing fields in a test case's constructor. After all, since a new instance of the test case is created for each of its test methods, the constructor is always called before setUp( ). In a vast majority of cases, you can use the constructor instead of setUp( ) without any side effects.

    In cases where your test case is part of a deeper inheritance hierarchy, you may wish to postpone object initialization until instances of derived classes are fully constructed. This is a good technical reason why you might want to use setUp( ) instead of a constructor for initialization. Using setUp( ) and tearDown( ) is also good for documentation purposes, simply because it may make the code easier to read.

提交回复
热议问题