Java – run each JUnit test using a separate classloader (no, really)

How can I have JUnit use a separate classloader for each test class it executes?

I'm writing a JUnit testrunner for a library that sets many static variables I basically want to reset all of these between each test class without knowing what they are I don't want to combine it with the intimate knowledge of the framework, because as long as the library changes internally, my testrunner will break

Before I leave, I want to make it clear that I really want to do this

>I don't have control of the library. > I didn't choose not to use static variables. > I don't want to use reflection or powermock because I don't want to know what's going on in the library. > I don't want to use Maven configuration to branch the test process, because the test utility is bound with the production tool

The other answers I can find on stackoverflow are just "don't do this", which doesn't help The first person to answer with "static variable is dumb" won a doughnut

Solution

Finally, I wrote myself, loosely based on another stack overflow answer (which is of no use to me)

Now in GitHub and Maven central https://github.com/BinaryTweed/quarantining-test-runner

<dependency>
    <groupId>com.binarytweed</groupId>
    <artifactId>quarantining-test-runner</artifactId>
    <version>0.0.1</version>
</dependency>

Use it to annotate your test class accordingly:

@RunWith(QuarantiningRunner.class)
@Quarantine({"com.binarytweed"})
public class MyIsolatedTest {
...

Because the test class itself needs to be loaded into a separate classloader, the linked answer does not work for me, because all referenced classes will use the same loader Isolation is inclusive (not exclusive) because you need the JUnit @ test annotation loaded by the parent classloader. Otherwise, JUnit cannot find any testable method because it uses class & test > as the key to find the map

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>