4

Using Junit 4.12. JUnit's Before annotation is documented, but it seems to me that it is no longer needed. Apparently JUnit creates a new instance for every 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 still need @Before?

tkruse
  • 10,222
  • 7
  • 53
  • 80
AlexC
  • 3,343
  • 6
  • 29
  • 38

1 Answers1

4

As in this similar question, methods annotated with @Before can usually be replaced with constructors / field initialization.

Some subtle differences exist that may make a difference in corner cases:

  • Exception Handling: Exceptions in @Before cause @After to be called, exceptions in constructor do not
  • Subclass initialization: @Before is called after the constructor has completed, allowing to access anything produced by child-class constructors
  • Subclassing: With @Before you can override parent class @Before methods, with constructors you always need to call one of the parent class constructors.
  • @Rule: The constructor is called before @Rule methods, @Before is called after @Rule methods
tkruse
  • 10,222
  • 7
  • 53
  • 80