如何使用powerMockito来模拟静态类

时间:2016-03-01 10:14:39

标签: java mockito powermockito

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassWithStatics.class})
public class mockTest  {
    @Test
    public void test() throws Exception {
        PowerMockito.mockStatic(ClassWithStatics.class);
           PowerMockito.when(ClassWithStatics.getString()).thenReturn("999");

    System.out.println("String: " + ClassWithStatics.getString());
    }

FAILED: test
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)
at com.autoTest.servicetest.mockTest.test(mockTest.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

0 个答案:

没有答案