JUnit的Powermock:本机库已在另一个类加载器中加载 [英] JUnit & Powermock: Native Library already loaded in another classloader
问题描述
我有一些测试类需要验证是否调用了GLFW函数。但是当我想在IntelliJ中执行所有测试时,我得到了错误:
I have some test classes that need to verify that GLFW-functions were called. But when I want to execute all tests in IntelliJ then I get the error:
Native Library lwjgl.dll already loaded in another classloader
我使用Powermock验证是否已调用静态方法:
I use Powermock to verify that the static methods have been called:
@RunWith(PowerMockRunner.class)
@PrepareForTest({GLFW.class})
public class GlfwWindowImplTest {
// ...
@Test
public void update_swapsBufferAndPollsEvents() {
GlfwWindowImpl target = new GlfwWindowImpl(1L);
mockStatic(GLFW.class);
target.update();
verifyStatic();
GLFW.glfwSwapBuffers(1L);
verifyStatic();
GLFW.glfwPollEvents();
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({GLFW.class})
public class GlfwWindowSystemImplTest {
// ...
@Test(expected = GlfwInitializeException.class)
public void initialize_throwsExceptionIfGlfwInitFails() {
GlfwWindowSystemImpl target = new GlfwWindowSystemImpl();
mockStatic(GLFW.class);
when(GLFW.glfwInit()).thenReturn(GL_FALSE);
target.initialize();
}
}
推荐答案
它回答这篇文章可能有点晚了,但是我遇到了类似的问题,并且我能够使用PowerMock解决它。 PowerMock具有 @SuppressStaticInitializationFor ,可以帮助您解决此问题。以下链接中的禁止静态初始化器部分提供了一个很好的示例:
It may be a bit late to answer this post, but I ran into a similar problem and I was able to solve it with PowerMock. PowerMock has @SuppressStaticInitializationFor that should help you overcome this issue. Section Suppress static initializer in the link below has a nice example about how to do that:
https://github.com/powermock/powermock/wiki/Suppress-Unwanted-Behavior
基本上,在您的情况下,可能会有一个调用 System.loadLibrary( lwjgl)的类。您需要找到该类。示例:
Basically, in your case, there could be a class that is calling System.loadLibrary("lwjgl"). You need to locate that class. Example:
public class SomeClass {
...
static {
System.loadLibrary ("lwjgl");
}
...
}
然后在测试中类使用 @SuppressStaticInitializationFor 和该类的完全限定名称:
Then in your test class use @SuppressStaticInitializationFor with the fully qualified name of the class:
@SuppressStaticInitializationFor("com.example.SomeClass")
如果执行loadLibrary调用的类是内部类,则您需要添加 $ InnerClass 以完全限定内部类。示例:
If in case the class doing the loadLibrary call is an inner class, then you need to add $InnerClass to fully qualify the inner class. Example:
public class SomeClass {
...
public static class SomeInnerClass {
static {
System.loadLibrary ("lwjgl");
}
}
...
}
然后您需要使用:
@SuppressStaticInitializationFor("com.example.SomeClass$SomeInnerClass")
这篇关于JUnit的Powermock:本机库已在另一个类加载器中加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!