2016-04-28 78 views
0

我試圖使用PowerMockito爲java.time.ZonedDateTime創建模擬,並期待ZonedDateTime的模擬對象。相反,實際的對象正在創建,因此我不能嘲笑ZonedDateTime類的方法。Powermock不爲java.time.ZonedDateTime創建模擬

以下是我的代碼片斷

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 
    } 
} 

除此之外,當我嘗試打印對象使用創建以下行 System.out.println(attribute.toString());

我得到異常以下:

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)

有人可以幫我解決這個問題嗎?我應該創建一個GitHub問題嗎?

回答

1

java.time.ZonedDateTime是一個最終的系統類,所以它只能通過使用workaround來模擬。解決方法要求將使用模擬系統類的類添加到@PrepareForTest。更多信息,請登錄documentation

但事件如果有可能模擬系統類,我想推薦你重構你的代碼,而不需要嘲笑系統類。因爲,不建議模擬類which you don't own.。你可以用有意義的方法創建一個util類。

0

在你的類像

public class SomeClass{ 

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

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

}

創建方法和測試類使用

@PrepareForTest(SomeClass.class) 

@RunWith(PowerMockRunner.class) 

在測試用例

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

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

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