Powermock does not create mock for java.time.Zoned

2019-01-20 19:24发布

问题:

I tried to create mock for java.time.ZonedDateTime using PowerMockito and I was expecting the mock object for ZonedDateTime. Instead, actual object is getting created and hence I cannot mock the methods of ZonedDateTime class.

Following is my code snippet

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ZonedDateTime.class})
public class ZonedDateTimeTest {

    @Test
    public void test(){
        ZonedDateTime attribute = mock(ZonedDateTime.class);
        when(attribute.format(any(DateTimeFormatter.class))).thenReturn("dummy");
        //test code here
    }
}

In addition to this, when I try to print the object created using following line System.out.println(attribute.toString());

I get following exception:

java.lang.NullPointerException at java.time.ZonedDateTime.toString(ZonedDateTime.java:2208) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:124) at org.powermock.core.MockGateway.methodCall(MockGateway.java:185)

Can someone please help me to workaround this? Should I create a GitHub issue?

回答1:

The java.time.ZonedDateTime is a final system class, so it could mocked only by using workaround. And the workaround requires that the class which uses mocked system class is added to @PrepareForTest. More information you may find in documentation.

But event if it possible to mock system classes, I'd like recommend you refactor your code in way that will not required mocking system classes. Because, it's not recommended to mock classes which you don't own.. You may create a util class with meaningful method.



回答2:

Create a method in your class like

public class SomeClass{

public static void main(String[] args) {
    LocalDateTime now = getCurrentLocalDateTime(); 
    System.out.println(now);
}

private LocalDateTime getCurrentLocalDateTime() {
    return LocalDateTime.now();
}

}

And in the Test Class you use

@PrepareForTest(SomeClass.class)

@RunWith(PowerMockRunner.class)

In TestCase

LocalDateTime tommorow= LocalDateTime.now().plusDays(1);

SomeClass classUnderTest = PowerMockito.spy(new SomeClass());

PowerMockito.when(classUnderTest, "getCurrentLocalDateTime").thenReturn(tommorow);


标签: powermock