简体   繁体   English

如何使用 Junit5 为每个测试使用单独的 class 加载程序

[英]How to have a separated class loader for each test using Junit5

I have been trying to set up a Junit 5 extension to force every test to get a separate ClassLoader.我一直在尝试设置一个 Junit 5 扩展来强制每个测试获得一个单独的 ClassLoader。 I am able to do it quite easily in Junit4, creating my own BlockJUnit4ClassRunner.我可以在 Junit4 中很容易地做到这一点,创建我自己的 BlockJUnit4ClassRunner。 But, I fail to have it work now.但是,我现在无法让它工作。

The purpose is to be able to test things such as static blocks or memorized fields in different states.目的是能够测试诸如 static 块或不同状态下的记忆字段之类的东西。

I have been trying to use the TestInstanceFactory without any success so far with something like that:到目前为止,我一直在尝试使用 TestInstanceFactory ,但没有成功:

public class SeparateClassLoaderExtension implements TestInstanceFactory {

    @SneakyThrows
    @Override
    public Object createTestInstance(TestInstanceFactoryContext factoryContext, ExtensionContext extensionContext) throws TestInstantiationException {
        ClassLoader testClassLoader = new TestClassLoader();
        final Class<?> testClass = Class.forName(factoryContext.getTestClass().getName(), true, testClassLoader);

        Constructor<?> defaultConstructor = testClass.getDeclaredConstructor();
        defaultConstructor.setAccessible(true);
        return defaultConstructor.newInstance();
    }
}

I get an exception from Junit saying that the class is not of the right type.我从 Junit 得到一个例外,说 class 类型不正确。

Someone any idea?有人知道吗?

JUnit Jupiter does not support this, yet. JUnit Jupiter尚不支持此功能。 Here's the related issue: https://github.com/junit-team/junit5/issues/201这是相关问题: https://github.com/junit-team/junit5/issues/201

They did something quite convoluted as Spring there .他们在那里做了一些非常令人费解的事情,例如 Spring 。

It looks like it is more or less working but it fails to function with another extension injection parameters and I did not go further.看起来它或多或少在工作,但它无法使用另一个扩展注入参数 function 并且我没有进一步 go 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM