Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

SeparateClassloaderTestRunner.java 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 static java.lang.ClassLoader.getSystemClassLoader;
  12. import java.net.URL;
  13. import java.net.URLClassLoader;
  14. import org.junit.runners.BlockJUnit4ClassRunner;
  15. import org.junit.runners.model.InitializationError;
  16. /**
  17. * This class is used when it's required to load jgit classes in separate
  18. * classloader for each test class. It can be needed to isolate static field
  19. * initialization between separate tests.
  20. */
  21. public class SeparateClassloaderTestRunner extends BlockJUnit4ClassRunner {
  22. /**
  23. * Creates a SeparateClassloaderTestRunner to run {@code klass}.
  24. *
  25. * @param klass
  26. * test class to run.
  27. * @throws InitializationError
  28. * if the test class is malformed or can't be found.
  29. */
  30. public SeparateClassloaderTestRunner(Class<?> klass)
  31. throws InitializationError {
  32. super(loadNewClass(klass));
  33. }
  34. private static Class<?> loadNewClass(Class<?> klass)
  35. throws InitializationError {
  36. try {
  37. URL[] urls = ((URLClassLoader) getSystemClassLoader()).getURLs();
  38. ClassLoader testClassLoader = new URLClassLoader(urls) {
  39. @Override
  40. public Class<?> loadClass(String name)
  41. throws ClassNotFoundException {
  42. if (name.startsWith("org.eclipse.jgit.")) {
  43. return super.findClass(name);
  44. }
  45. return super.loadClass(name);
  46. }
  47. };
  48. return Class.forName(klass.getName(), true, testClassLoader);
  49. } catch (ClassNotFoundException e) {
  50. throw new InitializationError(e);
  51. }
  52. }
  53. }