如何在Eclipse中运行使用旧版本的org.eclipse.equinox.common的JUnit测试?

时间:2017-08-08 09:00:29

标签: eclipse junit java-6 equinox eclipse-neon

当我在Eclipse Neon中运行使用org.eclipse.equinox.common 3.6和Java 6的测试时,我有时会收到以下错误:

pip3 freeze

似乎测试运行器加载了两个不同版本的org.eclipse.equinox.common。当我在调试视图中检查进程属性时,我看到(以及其他)类路径条目

java.lang.UnsupportedClassVersionError: org/eclipse/core/runtime/IAdapterManager : Unsupported major.minor version 51.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    ...

版本3.8需要Java 7,所以我想强制测试选择版本3.6。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

我找到了一个基于this answer解决问题的邪恶的类加载器黑客:

@BeforeClass
public static void setUpClass() throws Exception {
    removeJarFromClasspath("org.eclipse.equinox.common_3.8");
}

public static void removeJarFromClasspath(String namePart) throws Exception {
    URLClassLoader urlClassLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
    Field ucpField = URLClassLoader.class.getDeclaredField("ucp");
    ucpField.setAccessible(true);
    URLClassPath ucp = (URLClassPath)ucpField.get(urlClassLoader);

    Field pathField = URLClassPath.class.getDeclaredField("path");
    pathField.setAccessible(true);
    List path = (List)pathField.get(ucp);

    Field loadersField = URLClassPath.class.getDeclaredField("loaders");
    loadersField.setAccessible(true);
    List loaders = (List)loadersField.get(ucp);

    Field lmapField = URLClassPath.class.getDeclaredField("lmap");
    lmapField.setAccessible(true);
    Map lmap = (Map)lmapField.get(ucp);

    int index = 0;
    for (Object entry : path) {
        String url = entry.toString();
        if (url.contains(namePart)) {
            path.remove(index);
            loaders.remove(index);
            lmap.remove(url.replaceFirst("file:/", "file:///"));
            break;
        }
        index++;
    }
}