gpt4 book ai didi

java - 使用 PowerMock 时出现 ExceptionInInitializerError

转载 作者:太空宇宙 更新时间:2023-11-04 11:04:29 25 4
gpt4 key购买 nike

我有一个如下所示的测试类。需要在HmUtils.class内部模拟一个静态方法,

@RunWith(PowerMockRunner.class)
@PrepareForTest({Environment.class, HmUtils.class})
public class MyUtilTest {
@Mock
Context mockedContext;
@Before
public void initialSetup()
{
System.out.println("initSetup Executed:");
mockedContext = PowerMockito.mock(Context.class);
PowerMockito.mockStatic(Environment.class);
PowerMockito.mockStatic(HmUtils.class);
}
@Test
public void DeviceTest() throws Exception
{
System.out.println("DeviceTest Executed:");
when(Environment.getExternalStorageDirectory()).thenReturn(new File("testFile"));
when(Environment.getExternalStorageDirectory()
.getAbsolutePath()).thenReturn(anyString());
HmUtils.setCurrentBTAddress(null);
}

在 HmUtils.class 中,我有一个像这样的静态值(第 332 行)

public static final String TEST_FOLDER = Environment.getExternalStorageDirectory()
.getAbsolutePath();

这会抛出一个错误,例如“环境”getmethod 未被模拟。所以我模拟了环境类并尝试返回 getExternalStorageDirectory() 、 getAbsolutePath() 的值,如上所述。但仍然显示错误

java.lang.ExceptionInInitializerError
at sun.reflect.GeneratedSerializationConstructorAccessor12.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
Caused by: java.lang.NullPointerException
at com.package.android.app.mymanager.util.HmUtils.<clinit>(HmUtils.java:332)

最佳答案

LogUtils.class中,我在这一行中遇到错误

  public class LogUtils
{
private static final String TEST_FILE_FOLDER = Environment.getExternalStorageDirectory()
.getAbsolutePath();
}

LogUtilsTest.Class中,我通过下面的代码 fragment 解决了环境异常初始化错误

 @RunWith(PowerMockRunner.class)
@PrepareForTest({Environment.class})
public class LogUtilsTest {

private File file;

@Before
public void initialSetup() {
PowerMockito.mockStatic(Environment.class);
file = mock(File.class);
when(Environment.getExternalStorageDirectory()).thenReturn(file);
when(file.getAbsolutePath()).thenReturn("abc");
( OR )
//when(file.getAbsolutePath()).thenReturn(Mockito.anyString());
}

@Test
public void log_d() {
LogUtils.log_d("tag", "message");
}
}

关于java - 使用 PowerMock 时出现 ExceptionInInitializerError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46600068/

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