本文介绍了使用Powermock模拟类的构造函数时,出现ExceptionInInitializerError。如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的情况。我有一个AbstractController类。它有一个子类Controller。在AbstractController的一种方法中,实例化了一个新的ApplicationLock。我想在为Controller编写ut时模拟ApplicationLock。我写了一个如下的测试用例。

Here is my case. I have a AbstractController class. It has a sub class Controller. In one of AbstractController's methods a new ApplicationLock is instantiated. I'd like to mock ApplicationLock when writing ut for Controller. I wrote a test case like below.

@test
public void testMethod(){
    ApplicationLock mockLock=PowerMockito.mock(ApplicationLock.class);
    PowerMockito.when(mockLock.tryObtain()).thenReturn(true);
    PowerMockito.whenNew(ApplicationLock.class).withArguments(argThat(new IsFile()),anyString()).thenReturn(mockLock);
}

我已经在测试类中添加了必要的注释。

I've added necessary annotations to the test class.

@PrepareForTest({AbstractController.class})

@PrepareForTest({AbstractController.class})

但是运行此测试用例时出现以下错误。

But I got the following error when running this test case. That is a static initializer in AbstractController.

原因由:com.acompany.controller.common.AbstractController上的java.lang.NullPointerException
引起。 AbstractController.java:65)

private static final String DEFAULT_FOLDER = AbstractController.class.getProtectionDomain().getCodeSource()
            .getLocation().getPath();

完整的堆栈跟踪如下。


推荐答案

您可以使用:

 @SuppressStaticInitializationFor({AbstractController.class})

在您的测试用例中,手动设置所有需要初始化的静态字段,包​​括DEFAULT_FOLDER:

And then, in your test case, set manually all static fields that need to be initialized, including the DEFAULT_FOLDER:

Whitebox.setInternalState(Controller.class, "DEFAULT_FOLDER", "abcd");
Whitebox.setInternalState(Controller.class, "OTHER_FIELD", new Object());

方法 Class<?> .getProtectionDomain()在很大程度上取决于所使用的类加载器,因此您可能无法在使用它们的JUnit / PowerMock中使用它。

The method Class<?>.getProtectionDomain() depends too much on class loader used, so you probably won't get it to work in JUnit/PowerMock, which use their own.

这篇关于使用Powermock模拟类的构造函数时,出现ExceptionInInitializerError。如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 12:38