Is there a way to reinitialize a static class in J

2019-04-06 03:50发布

I'm trying to unit test a class that references static data from another class. I cannot "not" use this static class, but obviously running multiple tests has become problematic. So my question is this. Is there a way in a junit test to reinitialize a static class? That way one test is not effected by a previous test?

So in other words some way of doing this:

Foo.setBar("Hello");

// Somehow reinitialize Foo

String bar = Foo.getBar(); // Gets default value of bar rather than "Hello"

Unfortunately, I cannot change Foo, so I'm stuck using it.

Edit It appears I made my example a bit too simple. In the real code "Bar" is set by a system property and gets set to an internal static variable. So once it starts running, I can't change it.

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-06 04:21

Technically, it is possible to load the class (together with some other classes that are needed for the test) into its own class loader - you'd have to make sure that the class is not reachable from the root class loader, though, so it would require quite some hacking to do this, and I doubt it is possible in a normal unit test. Then you can drop the classloader and reinitialize it for the next test - each classloader has its own static variables for all classes loaded by it.

Alternatively, do it a bit more heavyweight and fork a new JVM for each test. I've done this before, it works (especially useful to do more complex integration tests that mess with system properties, which cannot easily be mocked otherwise), but it is probably not what you want for unit tests that run for every build...

Of course, these techniques can be also combined (if you don't get the class out of the root classloader) - fork a new JVM with a minimal "driver" on the classpath, that initializes a new classloader with the "normal" classpath for each test to run.

查看更多
登录 后发表回答