boden
boden

Reputation: 1681

Mockito error MissingMethodInvocationException

I'am writing test for my program, but I get exception on this part.

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

If I replace:

`HttpSession session = new MockHttpSession();`

to:

@Mock
private HttpSession session;

Method who need testing

public void method(HttpSession session){
    String value = session.getAttribute(SessionConstants.SESSION)
    List<String> result = new ArrayList();
    result.add(value);
    session.setAttribute(SessionConstants.SESSION, result);
}

If I use annotation @Mock i get #2 error, if I use MockHttpSession() i get #1 error

Its #1 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.

Upvotes: 2

Views: 1332

Answers (1)

EJK
EJK

Reputation: 12527

Although you have not posted the code for MockHttpSession, that appears to be a non-Mockito class which explains the error. As it states, when() can only be called on a mock created by Mockito.

You were right to then attempt to create the mock as follows:

@Mock
private HttpSession session;

However you left out the call that actually does the creation:

MockitoAnnotations.initMocks(this);

Add the above line to your test, preferrably in a setup method, and the when() call should work.

Upvotes: 3

Related Questions