我正在尝试模拟Calendar.getInstance()
以进行单元测试。
因此,我使用 PowerMock (powermock-core:2.0.4
& powermock-module-junit4:2.0.4
) 及其 Mockito API (powermock -api-mockito2:2.0.4
)。
我很清楚类似的案例do exist ,但我遇到了一个似乎没有出现在其他案例上的异常。
确实,在做的时候
mockStatic(Calendar.class);
when(Calendar.getInstance()).thenReturn(aCalendar);
在用
注释的类中的测试方法上@RunWith(PowerMockRunner.class)
@PrepareForTest({DateUtils.class})
我收到以下错误:org.mockito.exceptions.misusing.NotAMockException:参数应该是模拟,但是是:class java.lang.Class
。
我做错了什么以及如何解决?
谢谢
最佳答案
这里有几个问题。
mockStatic(Calendar.class);
这应该在 setUp 方法或其他方法中。
然后你就这样做。
verifyStatic(Calendar.class)
when(Calendar.getInstance()).thenReturn(aCalendar);
另一件重要的事情如下,
@RunWith(PowerMockRunner.class)
@PrepareForTest({DateUtils.class, Calendar.class})
任何具有您想要模拟的静态方法的类,如果仅使用一次,都应该在类级别或方法级别包含在 @PrepareForTest 中。
关于java - 在 Calendar.getInstance() 模拟中获取 NotAMockException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58749932/