简体   繁体   中英

Mocking class with static members

I need to write a junit4 test where I need to mock a class with a static member which produces java.lang.ExceptionInInitializerError if not mocked.

ClassToMock classToMock = mock(ClassToMock.class);
PowerMockito.whenNew(ClassToMock.class).withArguments(any()).thenReturn(classToMock);
StaticMember staticMember = mock(StaticMember.class);
PowerMockito.whenNew(StaticMember.class).withArguments(any()).thenReturn(staticMember);

And this is what my class looks like:

public class ClassToMock {
    public static final StaticMember staticMember_ = new StaticMemberDeserializer().deserialize("some argument");
}

Here StaticMemberDeserializer is a deserializer that uses some argument to create StaticMember.

Is there a way to directly mock the class ClassToMock ? If no, what can I do to avoid this error?

You need to prepare class to mock

@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.my.ClassToMock")

On test class level.

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