Ryan Ryan - 28 days ago 13
Java Question

Resetting a private static int from a junit test class

I am trying to write some junit tests for a class called Student. Basically, each student has a studentNum which is being set to an iterator which is a private static int. Every time a new Student is created, studentNum is incremented.

I have several tests for a function that gets the Student with a studentNum of 1 from a passed in arraylist of Students. However, each time I make a new arraylist of students in a new test, studentNum starts where the previous test's studentNum left off. So the first test will make Students with studentNums from 0 through 5, and the second test will make students with studentNums from 6 through 11.

I was wondering if there is a way to reset the private static studentNum integer from my test class, so that I can have it start at 0 for each test? Any help would be greatly appreaciated.

Answer

You can have a @Before or an @After (or both) in which you reset the private static field to whatever value you wish (e.g. 0), using Java's Reflection API.

The way to do that would be:

@Before
public void setup() throws Exception {
    Field studentNum = Student.class.getDeclaredField("studentNum");
    studentNum.setAccessible(true); //to overcome the visibility issue
    studentNum.setInt(null, 0); //null since it's static
}