gpt4 book ai didi

static - 静态类的 Powermock 给出错误 : java. lang.NoClassDefFoundError: Could not initialize class XXX

转载 作者:行者123 更新时间:2023-12-04 15:11:38 26 4
gpt4 key购买 nike

问题

无法初始化类...

  • ...javax.xml.transform.FactoryFinder(在我们的例子中)。
  • 在文章中,我们找到了解决方案,它是 SessionFactory 类。

被测类

我们想为具有静态成员的 utils 类编写测试。我们在尝试创建类的 Mock 时遇到错误,该类包含 new 语句作为静态字段的初始化。

public class ClassUnderTest{
private static JavaType javaType = new JavaType();
// ...
}

测试类

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassUnderTest.class)
public class TestForClassUnderTest {

@Test
public void testCase() {

PowerMockito.mockStatic(ClassUnderTest.class);

最佳答案

解决方案

解决方案是向测试类添加另一个类级别注释:

@SuppressStaticInitializationFor("com.example.package.util.ClassUnderTest")

请注意,您必须提供包路径并且末尾没有 .class。与 @PrepareFor 不同。

感谢这篇文章:http://www.gitshah.com/2010/06/how-to-suppress-static-initializers.html

带有解决方案的测试类

//...
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassUnderTest.class)
@SuppressStaticInitializationFor("com.example.package.util.ClassUnderTest") // <-- this is it :)
public class TestForClassUnderTest {

@Test
public void testCase() {
PowerMockito.mockStatic(ClassUnderTest.class);
//...
}
}

关于static - 静态类的 Powermock 给出错误 : java. lang.NoClassDefFoundError: Could not initialize class XXX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65129195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com