使用PowerMock时出现ExceptionInInitializerError

问题描述 投票:1回答:1

我有一个如下所示的Test类。需要在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没有被嘲笑。所以我模拟了Environment类,并尝试返回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)
java android junit mockito powermockito
1个回答
0
投票

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

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

在LogUtilsTest.Class中,我通过下面的代码片段解析环境异常初始化错误

 @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");
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.