gpt4 book ai didi

mocking - PowerMock 静态类不模拟

转载 作者:行者123 更新时间:2023-12-04 03:22:20 33 4
gpt4 key购买 nike

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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com