Mockito错误MissingMethodInvocationException

时间:2015-12-22 20:57:18

标签: java mockito

我正在为我的程序编写测试,但我在这方面有例外。

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

如果我更换:

`HttpSession session = new MockHttpSession();`

为:

@Mock
private HttpSession 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);
}

如果我使用注释@Mock我会收到#2错误,如果我使用MockHttpSession()我会收到#1错误

它的#1例外:

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.

1 个答案:

答案 0 :(得分:3)

虽然您尚未发布MockHttpSession的代码,但这似乎是一个解释错误的非Mockito类。正如它所述,when()只能在Mockito创建的模拟上调用。

您是正确的,然后尝试按如下方式创建模拟:

@Mock
private HttpSession session;

但是你遗漏了实际进行创作的电话:

MockitoAnnotations.initMocks(this);

将上述行添加到您的测试中,最好是在设置方法中,when()调用应该有效。