gpt4 book ai didi

java - 尝试模拟 java.lang.System 时出现 MockitoException

转载 作者:行者123 更新时间:2023-12-04 23:46:59 24 4
gpt4 key购买 nike

我有一个模拟 java.lang.System 的静态方法的测试用例类(class):

@Test
fun `getLocalTime()`() {
// Arrange
val staticMock = Mockito.mockStatic(System::class.java)
Mockito.`when`(System.currentTimeMillis()).thenReturn(1000L)

// Action
val res = deviceTimeProvider.getLocalTime()

// Assert
Truth.assertThat(res).isEqualTo(1000L)

staticMock.close()
}
但是当我运行测试时,我得到了这个错误:

org.mockito.exceptions.base.MockitoException: It is not possible tomock static methods of java.lang.System to avoid interfering withclass loading what leads to infinite loops


为什么会这样?如何模拟 java.lang.System 的方法类(class)?

最佳答案

而 Mockito 自 3.4.0版本允许模拟静态方法它不允许模拟 ThreadSystem静态方法,见 this comment on github

Finally note that Mockito forbids mocking the static methods of System (and Thread). Those methods are to much cemented into class loading which happens in the same thread. At some point, we might add instrumentation to class loading to temporarily disable the static mocks within it to make mocking these classes, too, where we also would need to disable their intensification properties. You can however easily mock Instant.now().

关于java - 尝试模拟 java.lang.System 时出现 MockitoException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64182348/

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