You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SeparateClassloaderTestRunner.java 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (C) 2019 Nail Samatov <sanail@yandex.ru> and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.junit;
  11. import java.net.MalformedURLException;
  12. import java.net.URL;
  13. import java.net.URLClassLoader;
  14. import java.nio.file.Paths;
  15. import org.junit.runners.BlockJUnit4ClassRunner;
  16. import org.junit.runners.model.InitializationError;
  17. /**
  18. * This class is used when it's required to load jgit classes in separate
  19. * classloader for each test class. It can be needed to isolate static field
  20. * initialization between separate tests.
  21. */
  22. public class SeparateClassloaderTestRunner extends BlockJUnit4ClassRunner {
  23. /**
  24. * Creates a SeparateClassloaderTestRunner to run {@code klass}.
  25. *
  26. * @param klass
  27. * test class to run.
  28. * @throws InitializationError
  29. * if the test class is malformed or can't be found.
  30. */
  31. public SeparateClassloaderTestRunner(Class<?> klass)
  32. throws InitializationError {
  33. super(loadNewClass(klass));
  34. }
  35. private static Class<?> loadNewClass(Class<?> klass)
  36. throws InitializationError {
  37. try {
  38. String pathSeparator = System.getProperty("path.separator");
  39. String[] classPathEntries = System.getProperty("java.class.path")
  40. .split(pathSeparator);
  41. URL[] urls = new URL[classPathEntries.length];
  42. for (int i = 0; i < classPathEntries.length; i++) {
  43. urls[i] = Paths.get(classPathEntries[i]).toUri().toURL();
  44. }
  45. ClassLoader testClassLoader = new URLClassLoader(urls) {
  46. @Override
  47. public Class<?> loadClass(String name)
  48. throws ClassNotFoundException {
  49. if (name.startsWith("org.eclipse.jgit.")) {
  50. return super.findClass(name);
  51. }
  52. return super.loadClass(name);
  53. }
  54. };
  55. return Class.forName(klass.getName(), true, testClassLoader);
  56. } catch (ClassNotFoundException | MalformedURLException e) {
  57. throw new InitializationError(e);
  58. }
  59. }
  60. }