【发布时间】:2016-05-03 03:53:23
【问题描述】:
我试图模拟一个新对象的创建
public class MyServiceTest {
MyClass myClass;
myClass = Mockito.mock(MyClass.class);
Mockito.when(new MyClass()).thenReturn(myClass);
}
错误:
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);
此外,出现此错误的原因可能是: 1.你存根:final/private/equals()/hashCode()方法。 这些方法不能被存根/验证。 不支持在非公共父类上声明的模拟方法。 2. 在 when() 中,你不会在 mock 上调用方法,而是在其他对象上调用。
我确实模拟了 myClass 对象,但它在方法调用时被分配给一个新对象:
public class MyService {
public static String myMethod(){
MyClass myClass = new MyClass();
//..........
}
}
【问题讨论】: