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

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

    I started digging myself and I found one potential advantage of using setUp(). If any exceptions are thrown during the execution of setUp(), JUnit will print a very helpful stack trace. On the other hand, if an exception is thrown during object construction, the error message simply says JUnit was unable to instantiate the test case and you don't see the line number where the failure occurred, probably because JUnit uses reflection to instantiate the test classes.

    None of this applies to the example of creating an empty collection, since that will never throw, but it is an advantage of the setUp() method.

提交回复
热议问题