JUnit: using constructor instead of @Before

前端 未结 8 790
旧巷少年郎
旧巷少年郎 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:58

    I prefer to use constructors to initialize my test objects because it allows me to make all the members final so that the IDE or compiler will tell me when the constructor forgot to initialize a member and prevent another method from setting them.

    IMHO, @Before violates one of the most important Java conventions, that of relying on the constructor to completely initalize objects!

    JUnit 5 also has better support for constructor injection.

    0 讨论(0)
  • 2020-12-04 15:04

    There is one thing that constructor can archive but not @Before.

    You have to use a constructor when you need to initial fields defined in parent class. For example:

    abstract class AbstractIT {
       int fieldAssignedInSubClass;
       public AbstractIT(int fieldAssignedInSubClass) {
          this.fieldAssignedInSubClass= fieldAssignedInSubClass;
       }
    
       @Before
       void before() {
          // comsume fieldAssignedInSubClass
       } 
    }
    
    public class ChildIT extends AbstractIT{
       public ChildIT() {
          // assign fieldAssignedInSubClass by constructor
          super(5566); 
       }
    
       @Before
       void before() {
          // you cannot assign fieldAssignedInSubClass by a @Before method
       } 
    }
    
    0 讨论(0)
提交回复
热议问题