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.
You can try this. Main MainObject = new Main; MainObject. main(args); It will restart the class again and again until you stop the class.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With