Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a separated class loader for each test using Junit5

Tags:

java

junit5

I have been trying to set up a Junit 5 extension to force every test to get a separate ClassLoader. I am able to do it quite easily in Junit4, creating my own BlockJUnit4ClassRunner. But, I fail to have it work now.

The purpose is to be able to test things such as static blocks or memorized fields in different states.

I have been trying to use the TestInstanceFactory without any success so far with something like that:

public class SeparateClassLoaderExtension implements TestInstanceFactory {

    @SneakyThrows
    @Override
    public Object createTestInstance(TestInstanceFactoryContext factoryContext, ExtensionContext extensionContext) throws TestInstantiationException {
        ClassLoader testClassLoader = new TestClassLoader();
        final Class<?> testClass = Class.forName(factoryContext.getTestClass().getName(), true, testClassLoader);

        Constructor<?> defaultConstructor = testClass.getDeclaredConstructor();
        defaultConstructor.setAccessible(true);
        return defaultConstructor.newInstance();
    }
}

I get an exception from Junit saying that the class is not of the right type.

Someone any idea?

like image 562
Arnaud Villevieille Avatar asked Oct 16 '22 09:10

Arnaud Villevieille


1 Answers

JUnit Jupiter does not support this, yet. Here's the related issue: https://github.com/junit-team/junit5/issues/201

like image 166
Sormuras Avatar answered Oct 21 '22 03:10

Sormuras