Does Junit reinitialize the class with each test method invocation?

Prateek picture Prateek · Oct 15, 2013 · Viewed 7.7k times · Source

When i run the below code, both test cases come true:

import static junit.framework.Assert.assertEquals;

import org.junit.Test;

public class MyTest{
    private int count;

    @Before
    public void before(){
        count=1;
    }

    @Test
    public void test1(){
        count++;
        assertEquals(2, count); 
    }

    @Test
    public void test2(){
        count++;
        assertEquals(2, count); 
    }
}

EXPECTED BEHAVIOUR

  1. test1 - success
  2. test2 - fail(as expected that count will become 3)

ACTUAL BEHAVIOUR

  1. test1 - success
  2. test2 - success

Why junit is reinitializing class/variable with each test method invocation. It is a bug in junit or is provided intentionally.

Answer

René Link picture René Link · Oct 15, 2013

It is because of test isolation.

No test should depend on another.