【发布时间】:2016-06-02 15:39:48
【问题描述】:
我正在尝试模拟静态方法 Instant.now(),并且在尝试模拟 java.time 包中的类时,我继续遇到奇怪的行为。请在下面查看我的代码以尝试模拟 Instant.now()
@RunWith(PowerMockRunner.class)
@PrepareForTest(Instant.class)
public class UnitTestClasss {
@Test
public void unitTestMethod() throws Exception {
mockCurrentTimeAtMidNight();
instanceOfSystemUnderTest.someMethodDependingOnTime();
assertHandledHere();
}
/*See First Error Below */
private void mockCurrentTimeAtMidNight() {
ZonedDateTime current = ZonedDateTime.now();
ZonedDateTime mockMidNight = ZonedDateTime.of(current.getYear(), current.getMonthValue(),
current.getDayOfMonth(), 0, 0, 0, 0,current.getZone());
PowerMockito.mockStatic(Instant.class);
PowerMockito.when(Instant.now()).thenReturn(Instant.from(mockMidNight));
}
/*See Second Error Below */
private void mockCurrentTimeAtMidNight2() {
Calendar cal = Calendar.getInstance();
ZonedDateTime mockMidNight = ZonedDateTime.of(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0, 0,ZoneId.of("US/Eastern"));
Instant instant = mockMidNight.toInstant();
PowerMockito.mockStatic(Instant.class);
PowerMockito.when(Instant.now()).thenReturn(instant);
}
}
错误 1 org.mockito.exceptions.misusing.UnfinishedStubbingException: 此处检测到未完成的存根: -> 在 org.powermock.api.mockito.PowerMockito.when(PowerMockito.java:495)
E.g. thenReturn() may be missing. Examples of correct stubbing: when(mock.isOk()).thenReturn(true); when(mock.isOk()).thenThrow(exception); doThrow(exception).when(mock).someVoidMethod(); Hints: 1. missing thenReturn() 2. you are trying to stub a final method, you naughty developer! 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed错误 2:原因:[源错误]
toInstant()未在java.time.ZonedDateTime
【问题讨论】:
-
你为什么不创建一个 mock/fake
Clock来代替? -
@dcsohl 它从 ChronoZonedDateTime 获取它,对于 isEquals(...) 方法也相同。但我也遇到了同样的错误
-
请参阅detailed answer 以及关于模拟 Instant 的代码示例
标签: java unit-testing mockito powermock