我有一个测试类,如下所示。需要模拟 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 中,我通过以下代码片段解决环境异常初始化器错误
@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");
}
}