首页 > 解决方案 > 在 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

我做错了什么以及如何解决?

谢谢

标签: javaandroidunit-testingpowermockito

解决方案


这里有几个问题。

mockStatic(Calendar.class);这应该在 setUp 方法或其他东西中。

然后你这样做。

verifyStatic(Calendar.class)
when(Calendar.getInstance()).thenReturn(aCalendar);

另一个重要的事情是以下,

@RunWith(PowerMockRunner.class)
@PrepareForTest({DateUtils.class, Calendar.class})

任何具有您想要模拟的静态方法的类都应该在类级别或方法级别包含在 @PrepareForTest 中,如果它只使用一次。


推荐阅读