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