Java Mockito错误缺少MethodInvocationException
我正在为我的程序编写测试,但我在这一部分遇到了异常Java Mockito错误缺少MethodInvocationException,java,mockito,Java,Mockito,我正在为我的程序编写测试,但我在这一部分遇到了异常 @Test public void test(){ HttpSession session = new MockHttpSession(); //other code ... // #1 MissingMethodInvocationException when(session.getAttribute(SessionConstants.SESSION)).thenReturn(image); r
@Test
public void test(){
HttpSession session = new MockHttpSession();
//other code
...
// #1 MissingMethodInvocationException
when(session.getAttribute(SessionConstants.SESSION)).thenReturn(image);
runClassMyApp.method(session);
// #2 I can't get attribute from session I get `null`.
List<MyClass> = (ArrayList) session.getAttribute(SessionConstants.SESSION);
}
致:
需要测试的方法
public void method(HttpSession session){
String value = session.getAttribute(SessionConstants.SESSION)
List<String> result = new ArrayList();
result.add(value);
session.setAttribute(SessionConstants.SESSION, result);
}
虽然您还没有发布MockHttpSession的代码,但这似乎是解释错误的非Mockito类。正如它所述,
when()
只能在Mockito创建的mock上调用
然后您正确地尝试创建模拟,如下所示:
@Mock
private HttpSession session;
但是,您忽略了实际执行创建的调用:
MockitoAnnotations.initMocks(this);
将上述行添加到测试中,最好是在设置方法中,并且
when()
调用应该可以工作。I'am AddMockitoAnnotations.initMocks(session)使用@Mock
进行编码>和创建,但这没有帮助。请参阅新代码
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.
@Mock
private HttpSession session;
MockitoAnnotations.initMocks(this);