PowerMock静态类不会模拟

Sam*_*Sam 9 testng static-methods mocking mockito

public class TestStatic {
    public static int methodstatic(){
        return 3;
    }
}


@Test
@PrepareForTest({TestStatic.class})
public class TestStaticTest extends PowerMockTestCase {

    public void testMethodstatic() throws Exception {
        PowerMockito.mock(TestStatic.class);
        Mockito.when(TestStatic.methodstatic()).thenReturn(5);
        PowerMockito.verifyStatic();
        assertThat("dff",TestStatic.methodstatic()==5);
    }

    @ObjectFactory
    public IObjectFactory getObjectFactory() {
        return new org.powermock.modules.testng.PowerMockObjectFactory();
    }
}
Run Code Online (Sandbox Code Playgroud)

例外:

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.
2. inside when() you don't call method on mock but on some other object.
Run Code Online (Sandbox Code Playgroud)

我通过Intellij运行它,遗留代码有很多方法......

有人有想法,我通过官方tuto,没有意义使这个简单的测试工作

小智 10

在我的案例中,我找到了解决此问题的方法,希望与您分享:

如果我在测试类中调用了mocked方法:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Calendar.class)
public class TestClass {
  @Test
  public void testGetDefaultDeploymentTime()
    PowerMockito.mockStatic(Calendar.class);
    Calendar calendar = new GregorianCalendar();
    calendar.set(Calendar.HOUR_OF_DAY, 8);
    calendar.set(Calendar.MINUTE, 0);
    when(Calendar.getInstance()).thenReturn(calendar);
    Calendar.getInstance();
  }
}
Run Code Online (Sandbox Code Playgroud)

它运作得很好.但是当我重新编写测试时,它在另一个类中调用了Calendar.getInstance(),它使用了真正的Calendar方法.

@Test
public void testGetDefaultDeploymentTime() throws Exception {
  mockUserBehaviour();
  new AnotherClass().anotherClassMethodCall();    // Calendar.getInstance is called here
}
Run Code Online (Sandbox Code Playgroud)

因此,作为一种解决方案,我将AnotherClass.class添加到@PrepareForTest,现在可以正常工作了.

@PrepareForTest({Calendar.class, AnotherClass.class})
Run Code Online (Sandbox Code Playgroud)

似乎PowerMock需要知道将调用模拟静态方法的位置.


Bri*_*ice 0

看看这个答案:Mocking Logger and LoggerFactory with PowerMock and Mockito

Mockito.when另外,如果您想存根静态调用,则不应该使用,但是PowerMockito.when.

静态是可测试性的噩梦,您要尽可能避免这种情况,并重新设计您的设计,以便不再使用静态或不必使用 PowerMock 技巧来测试您的生产代码。