mocking - PowerMock 静态类不模拟

标签 mocking testng static-methods 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();
    }
}

异常(exception):
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.

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

有人有想法,我通过了官方教程,并不意味着让这个简单的测试工作

最佳答案

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

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

@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();
  }
}

它工作得很好。但是当我重写测试时,它在另一个类中调用 Calendar.getInstance() 它使用了真正的 Calendar 方法。
@Test
public void testGetDefaultDeploymentTime() throws Exception {
  mockUserBehaviour();
  new AnotherClass().anotherClassMethodCall();    // Calendar.getInstance is called here
}

所以,作为一个解决方案,我将 AnotherClass.class 添加到 @PrepareForTest 并且它现在可以工作了。
@PrepareForTest({Calendar.class, AnotherClass.class})

PowerMock 似乎需要知道在哪里调用模拟的静态方法。

关于mocking - PowerMock 静态类不模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12420410/

相关文章:

python - 在类级容器初始化中调用静态方法

javascript - 是否可以从继承的工厂方法一般实例化 JS 类类型?

asp.net-mvc - 如何在MVC单元测试类中模拟Request.Files[]?

java - 你会像 "inherit and override"一样模拟被测试的类吗?

java - 在 Java 函数中使用数组初始化器

eclipse - 从 Eclipse 运行 TestNG testng.xml 测试

java - 通过 TestNG 运行 Selenium 时出现空指针异常

java - 用 Java 构建一个可模拟的日志记录 API,正确的方法

java - 使用 PowerMock 模拟静态和动态方法

java - Jenkins 无法运行 xml