Reputation: 1119
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?
Upvotes: 7
Views: 1807
Reputation: 380
According to the Junit documentation, the way to set a custom classloader for tests in Junit 5 is to create a LauncherInterceptor and configure it using by setting a system property e.g. in gradle:
test {
systemProperty(”junit.platform.launcher.interceptors.enabled“, true)
// ...
}
Then then LauncherInterceptor needs to be registered by adding it to /META-INF/services/org.junit.platform.launcher.LauncherDiscoveryListener
Upvotes: 0
Reputation: 9099
JUnit Jupiter does not support this, yet. Here's the related issue: https://github.com/junit-team/junit5/issues/201
Upvotes: 3