我试图伪装静态方法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)处的-> 例如,thenReturn()可能丢失了。正确固执的例子: when(mock.isOk()).thenReturn(true);when(mock.isOk().thenThrow(Exception));.thenThrow提示: 1.缺少thenReturn() 2.您正在尝试对最后一个方法进行存根,您这个淘气的开发人员!3:如果完成了'thenReturn‘指令,您就会在’thenReturn‘指令之前将另一个模拟的行为顽固不化。 错误2:有原因:在
toInstant()中找不到源错误java.time.ZonedDateTime
发布于 2016-06-14 23:16:22
从我所能知道的情况来看,我得到了错误,因为最初我在单元测试中调用.now(),然后尝试在之后模拟它。之所以这样做是因为我认为我可以让我的测试使用非模拟的方法,然后模拟它,这样我的SUT就可以使用模拟的表单了。
最后,我改变了这一点,转而嘲弄了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()来处理我的Test类,而我的SUT源代码则使用了.ofInstant(...)。
发布于 2016-06-02 20:49:26
您试图模拟一个java.time类,这意味着您试图模拟一个系统类。这需要您进行在@PrepareForTest注释中测试您自己的系统,因为PowerMock无法拦截您调用的类的加载,因此它必须拦截类的加载,并在那里执行字节码重写。
(这与您的错误消息并不完全一致,但这仍然是您在这里遇到麻烦的一个非常明显的原因,而在Mockito和PowerMock中的非系统类则不然。)
模拟系统类的危险--再加上您在模拟数据对象,特别是具有显式单元测试功能的对象(如注释中提到的时钟覆盖),-are是不使用模拟的一个很好的理由。
https://stackoverflow.com/questions/37596377
复制相似问题