Mockito中的模拟静态类



我有如下内容:

    public class Foo {
    public static String getValue(String key) {
        return key + "_" + System.currentTimeMillis();
    }
}

现在我需要一个测试用例,下面是我的尝试:

@Test
public void testFoo() {
   PowerMockito.mockStatic(Foo.class);
    PowerMockito.when(Foo.getValue("123")).thenReturn("abcd");
    PowerMockito.verifyStatic();
}

当我运行测试用例时,我得到的是:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
    at org.powermock.api.mockito.PowerMockito.when(PowerMockito.java:495)

我做错什么了吗?

请告知。

您能确认您已经在PowerMock网站上列出的测试类上添加了@PrepareForTest(Foo.class)注释,并且您正在使用PowerMockRunner JUnit4 runner吗?

静态方法是通过静态调度调用的,而不是使用Java的普通多态性和方法重写的动态调度。为了替换实现,PowerMock需要在测试开始运行之前加载一个替换类,而runner和annotation实现了这一点。

相关内容

  • 没有找到相关文章

最新更新