Skip to content

Instantly share code, notes, and snippets.

@cataphract
Created August 30, 2019 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cataphract/fac9b646e3139ea0a0a77cb40f157742 to your computer and use it in GitHub Desktop.
Save cataphract/fac9b646e3139ea0a0a77cb40f157742 to your computer and use it in GitHub Desktop.
package io.sqreen.powerwaf.test;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestClass;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Loads the test in a separate classloader. The URLs of the classloader
* for non-delegated classes are those of the source and test classes.
*/
public class SeparateClassloaderRunner extends BlockJUnit4ClassRunner {
public SeparateClassloaderRunner(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
protected TestClass createTestClass(Class<?> testClass) {
return super.createTestClass(replaceClass(testClass));
}
private ChildFirstURLClassLoader cl;
private Class<?> replaceClass(Class<?> klass) {
ClassLoader parentCl = klass.getClassLoader();
String urlSrc = parentCl.getResource("io/sqreen/powerwaf/Powerwaf.class").getFile();
int endOfDirSrc = urlSrc.indexOf("io/sqreen/");
String srcClassesDir = urlSrc.substring(0, endOfDirSrc);
String urlTest = parentCl.getResource("io/sqreen/powerwaf/test/SeparateClassloaderRunner.class").getFile();
int endOfDirTest = urlTest.indexOf("io/sqreen/");
String testClassesDir = urlTest.substring(0, endOfDirTest);
ChildFirstURLClassLoader cl;
try {
cl = new ChildFirstURLClassLoader(
new URL[] {
new URL("file://" + srcClassesDir),
new URL("file://" + testClassesDir),
}, parentCl);
} catch (MalformedURLException e) {
throw new UndeclaredThrowableException(e);
}
String klassName = klass.getName();
try {
return cl.loadClass(klassName, false, false);
} catch (Exception e) {
throw new UndeclaredThrowableException(e);
}
}
@Override
protected Statement classBlock(RunNotifier notifier) {
final Statement superStatement = super.classBlock(notifier);
return new Statement() {
@Override
public void evaluate() throws Throwable {
superStatement.evaluate();
System.gc();
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment