[英]ExceptionInInitializerError when using PowerMock
I have a Test class like below. 我有一个像下面的测试课。 Need to mock a static method inside HmUtils.class,
需要在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);
}
In HmUtils.class , I have a static value like this (in line 332) 在HmUtils.class中,我有一个像这样的静态值(第332行)
public static final String TEST_FOLDER = Environment.getExternalStorageDirectory()
.getAbsolutePath();
This throw a error like "Environment" getmethod is not mocked. 这不会抛出类似“ Environment” getmethod的错误。 so I have mocked Environment class and try to return a value for the getExternalStorageDirectory() , getAbsolutePath() as above.
因此,我模拟了Environment类,并尝试为上述的getExternalStorageDirectory()和getAbsolutePath()返回值。 but still it shows error
但它仍然显示错误
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)
In LogUtils.class , I got error in this line 在LogUtils.class中 ,此行出现错误
public class LogUtils
{
private static final String TEST_FILE_FOLDER = Environment.getExternalStorageDirectory()
.getAbsolutePath();
}
In LogUtilsTest.Class I resolve Environment exceptionininitializererror by below snippet 在LogUtilsTest.Class中,我通过以下代码段解决了环境exceptionininitializererror
@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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.