【问题标题】:Getting NotAMockException on Calendar.getInstance() mocking在 Calendar.getInstance() 模拟上获取 NotAMockException
【发布时间】:2019-11-07 13:37:24
【问题描述】:

我正在尝试模拟 Calendar.getInstance() 以进行单元测试。

因此,我正在使用 PowerMock (powermock-core:2.0.4 & powermock-module-junit4:2.0.4) 及其 Mockito API (powermock-api-mockito2:2.0.4)。

我很清楚类似的情况doexist,但我面临一个似乎没有出现在其他情况下的异常。

确实,在做的时候

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

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

谢谢

【问题讨论】:

    标签: java android unit-testing powermockito


    【解决方案1】:

    这里有几个问题。

    mockStatic(Calendar.class);这应该在setUp方法之类的。

    然后你这样做。

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

    另外一个重要的事情如下,

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      相关资源
      最近更新 更多