我读了几篇有关使用powermockito而不是仅仅用嘲讽来测试静态方法的文章,但是在切换到Power Mockito之后,我仍然遇到相同的错误。以下是我的课程和例外。例外情况都不能解释我的错误。
@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassToBeMocked.class})
public class Test extends AbstractTestNGSpringContextTests {
@Mock
Object1 o1;
@BeforeMethod
public void init() {
mockStatic(ClassToBeMocked.class);
PowerMockito.when(ClassToBeMocked.getMethod()).thenReturn("string");
}
最后一行代码导致此异常org.mockito.exceptions.misusing.MissingMethodInvocationException:when()需要一个参数,该参数必须是“模拟的方法调用”。例如:when(mock.getArticles())。thenReturn(articles;
此外,由于以下原因,可能会出现此错误:1.存根:final / private / equals()/ hashCode()方法之一。那些方法[[无法被存根/验证。不支持在非公共父类上声明的模拟方法。2.在when()内部,您不会在模拟对象上调用方法,而是在其他某个对象上调用。
@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassToBeMocked.class})
public class Test extends PowerMockTestCase {
@Mock
Object1 o1;
@ObjectFactory
public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
@BeforeMethod
public void init() {
mockStatic(ClassToBeMocked.class);
PowerMockito.when(ClassToBeMocked.getMethod()).thenReturn("string");
}
@ RunWith(PowerMockRunner.class)将无法像使用org.junit.Before那样拾取@BeforeMethod。另外,AbstractTestNGSpringContextTests不能与@Mock一起使用。