Do we still need JUnit before annotating?

Using Junit 4.12. JUnit Before annotations are documented, but it seems to me that it is no longer needed. Apparently, JUnit creates a new instance for each test, as shown in the following snippet:

import org.junit.Test;

public class BeforeTest {
TestObject testObject = new TestObject();

@Test
public void one(){
    System.out.println(testObject.status);
    testObject.setStatus("Used by one()");
}

@Test
public void two(){
    System.out.println(testObject.status);
    testObject.setStatus("Used by two()");
}


private class TestObject{
    public String status;

    public TestObject(){
        status = "new";
    }

    void setStatus(String newStatus){status = newStatus;}
}

}

-----------------------------
new
new

Do we need @Before?

+4
source share
1 answer

As in this similar question , methods annotated with help @Beforecan usually be replaced with initializing constructors / fields.

There are some subtle differences that can make a difference in angular cases:

  • Exception handling: exceptions in @Before reason @ After calling exceptions in the constructor, do not
  • : @Before , -,
  • : @Before @Before, .
  • @Rule: @Rule, @Before @Rule
+4

Source: https://habr.com/ru/post/1692279/


All Articles