user549904
user549904

Reputation: 33

JUnit makes a new instance of the class without @BeforeEach?

In order to refactor testing, we are taught that JUnit will make a new instance of the class every time by doing the following:

public class someClassTest{

  final private someClass obj1 = new someClass();

  @Test
  public void t1() {
      Assertions.assertEquals(1, obj1.returnOne());
  }

  @Test
  public void t2() {
      Assertions.assertEquals(8, obj1.return(2));
  }
}

Rather than using something like

@BeforeEach
void setup(){
someClass obj1 = new someClass();}

or initializing it inside the test methods every time.

My question is, why and how does my first block of code work to achieve the same purpose as the @BeforeEach?

Upvotes: 3

Views: 483

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42441

JUnit framework manages that. It creates a new instance of the test class (someClassTest) before each test.

Take a look at this example:

public class SampleTest {

    @Test
    public void test1() {
        System.out.println(this.toString());
    }

    @Test
    public void test2() {
        System.out.println(this.toString());
    }
}

Run it and you'll see that the test class instance is different in test1 and test2, for example:

SampleTest@4e515669
SampleTest@504bae78

From that point is just an ordinary behavior of Java. If you have a field in an object, it will be re-created (and re-initialized):

public class SampleTest {
   private int i = 0;

   @Test
   public void test1() {
      // i is 0, so lets increase and see what happens in test2
      i++;
   }
   @Test
   public void test2() {
     // here i is again 0 because it was re-created, we have a different object of SampleTest 

   }
}

Upvotes: 3

Related Questions