繁体   English   中英

模拟内联不完整的模拟特定方法 class

[英]Mock specific method with mockito-inline not complete class

我想模拟 class 的 static 方法。 当我使用 mockito-inline 时,它会模拟完整的 class 而不是 mocking 特定方法。 我的目标是它应该只模拟我想要的方法。 其他人应该保持不变(原样)。

@Test
     public void myTest() throws Exception {
         ZonedDateTime mockDateTime = ZonedDateTime.of(2022, 1, 1, 10, 10, 10, 100, ZoneId.of(DEFAULT_ZONE_ID));
          try (MockedStatic<ZonedDateTime> zonedTime = Mockito.mockStatic(ZonedDateTime.class)) {
              zonedTime.when(() -> ZonedDateTime.now(ZoneId.of(DEFAULT_ZONE_ID))).thenReturn(mockDateTime);

         // Zoned time will be called inside myMethod
            ZonedDateTime zonedDateTime = myClass.myMethod();
            System.out.println("Result: "+ zonedDateTime);
          }

在上面的代码中,我是 mocking ZonedDateTime.now()方法,但由于某种原因,其他方法也被嘲笑,例如ZonedDateTime.parse()等,因为我没有为他们提供任何模拟,他们正在返回null对于那些未模拟的方法。 理想情况下,通常的实施应该可以工作。

我正在寻找一些改变,所有原始方法都应该到位。

文档模拟中所述,默认情况下返回 null/空值。 API for creating static spies which would include the default behavior by default is not currently defined, so you have to tell Mockito to call the actual methods on the mock either by calling when(...).thenCallRealMethod() or by using the CALLS_REAL_METHODS调用mockStatic方法时的常量Answer

try (MockedStatic<ZonedDateTime> zonedTime = Mockito.mockStatic(ZonedDateTime.class, CALLS_REAL_METHODS)) {
    // ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM