java - 在 Calendar.getInstance() 模拟上获取 NotAMockException
问题描述
我试图模拟Calendar.getInstance()
单元测试的目的。
因此,我正在使用 PowerMock ( powermock-core:2.0.4
& powermock-module-junit4:2.0.4
) 及其 Mockito API ( powermock-api-mockito2:2.0.4
)。
我很清楚确实 存在类似的案例,但我面临一个似乎没有出现在其他案例中的异常。
确实,做的时候
mockStatic(Calendar.class);
when(Calendar.getInstance()).thenReturn(aCalendar);
在带有注释的类中的测试方法上
@RunWith(PowerMockRunner.class)
@PrepareForTest({DateUtils.class})
我收到以下错误:org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: 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 中,如果它只使用一次。
推荐阅读
- google-cloud-platform - Ansible GCP IAP 隧道
- c++ - Solaris11.3 OS 中 fwrite 调用后文件位置不正确
- javascript - 子进程会阻塞 node.js 中的父进程吗?
- google-cloud-platform - 传递多个过滤器选项
- c++ - 如何在给定的文本中用字符数组替换符号
- apache-kafka - 卡夫卡生产者卡住了
- python - 在numpy中从一个数组到另一个数组获取下一个日期的天数
- excel - VBA根据单元格引用更改OLAP数据透视表过滤器
- git - Git如何从分支中删除旧的提交?
- ruby - ruby - attr - 我应该使用@还是没有@的getter?