在 Mockito 中模拟静态 class
Mocking static class in 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)
我做错了什么吗?
请指教
您能否确认您已将 @PrepareForTest(Foo.class)
注释添加到您的测试 class 中,如所列 on the PowerMock site, and that you're using the PowerMockRunner JUnit4 运行器?
静态方法是使用静态分派调用的,而不是使用 Java 的正常多态性和方法覆盖的动态分派。要替换实现,PowerMock 需要在测试开始 运行 之前加载替换 class,而运行器和注释会实现这一点。
我有如下内容:
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)
我做错了什么吗?
请指教
您能否确认您已将 @PrepareForTest(Foo.class)
注释添加到您的测试 class 中,如所列 on the PowerMock site, and that you're using the PowerMockRunner JUnit4 运行器?
静态方法是使用静态分派调用的,而不是使用 Java 的正常多态性和方法覆盖的动态分派。要替换实现,PowerMock 需要在测试开始 运行 之前加载替换 class,而运行器和注释会实现这一点。