Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset class static variable during unit test

I am trying to write a unit test for a legacy code. The class which I'm testing has several static variables. My test case class has a few @Test methods. Hence all of them share the same state.

Is there way to reset all static variables between tests?

One solution I came up is to explicitly reset each field, e.g.:

field(MyUnit.class, "staticString").set(null, null);
((Map) field(MyUnit.class, "staticFinalHashMap").get(null)).clear();

As you see, each variable needs custom re-initialization. The approach is not easy to scale, there are a lot such classes in the legacy code base. Is there any way to reset everything at once? Maybe by reloading the class each time?

As a possible good solution I think is to use something like powermock and create a separate classloader for each test. But I don't see easy way to do it.

like image 953
kan Avatar asked Aug 06 '12 14:08

kan


People also ask

How do you reset a static class in Java?

You can try this. Main MainObject = new Main; MainObject. main(args); It will restart the class again and again until you stop the class.

Can static class variables be changed?

In simple words, if you use a static keyword with a variable or a method inside a class, then for every instance that you create for that class, these static members remain constant and you can't change or modify them.

How do you initialize a static variable in Junit?

You could call the main method of classA . i.e. ClassA. main(somestrArray) and it should do the initialization. But if you don't want to do that then you could create your junit test in the same package as the original class and you would be able to access the protected variables .


1 Answers

Ok, I think I figured it out. It is very simple.

It is possible to move @PrepareForTest powermock's annotation to the method level. In this case powermock creates classloader per method. So it does that I need.

like image 191
kan Avatar answered Sep 21 '22 11:09

kan