简体   繁体   中英

ExceptionInInitializerError when using PowerMock

I have a Test class like below. Need to mock a static method inside 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)

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

This throw a error like "Environment" getmethod is not mocked. so I have mocked Environment class and try to return a value for the getExternalStorageDirectory() , getAbsolutePath() as above. 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

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

In LogUtilsTest.Class I resolve Environment exceptionininitializererror by below snippet

 @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");
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM