Reset class static variable during unit test

kan picture kan · Aug 6, 2012 · Viewed 20.5k times · Source

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.

Answer

kan picture kan · Aug 6, 2012

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.