gpt4 book ai didi

Java PowerMockito 模拟 Instant.now()

转载 作者:行者123 更新时间:2023-12-02 01:52:09 25 4
gpt4 key购买 nike

我正在尝试模拟静态方法 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);
}

}

Errors 1 org.mockito.exceptions.misusing.UnfinishedStubbingException: Unfinished stubbing detected here: -> at 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

Errors 2: with Reason: [source error] toInstant() not found in java.time.ZonedDateTime

最佳答案

据我所知,我收到了错误,因为最初我在单元测试中调用 .now() ,然后尝试模拟它。这样做的原因是因为我认为我可以让我的测试使用未模拟的方法然后模拟它,这样我的 SUT 就可以使用模拟的形式。

我最终对此进行了一些更改并 mock 了 ZonedDateTime.ofInstant(obj,obj) 。这就是我所做的

@Test
public void renamingToArbitraryMethodName() throws Exception {
ZonedDateTime current = ZonedDateTime.now();
ZonedDateTime mockMidNight = ZonedDateTime.of(current.getYear(), current.getMonthValue(),
current.getDayOfMonth(), 0, 0, 0, 0, ZoneId.of("US/Eastern"));

PowerMockito.mockStatic(ZonedDateTime.class);
PowerMockito.when(ZonedDateTime.ofInstant(anyObject(), anyObject())).thenReturn(mockTime);
}

在我的场景中,这对我有用,因为我能够使用 .now() 摆脱我的测试类,而我的 SUT 源使用 .ofInstant(...)

关于Java PowerMockito 模拟 Instant.now(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37596377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com