我正在为我的程序编写测试,但我在这部分遇到了异常。
@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错误
它的第一个例外:
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.
虽然您还没有发布MockHttpSession的代码,但它似乎是一个非Mockito类,可以解释错误。正如它所说,when()
只能在Mockito创建的mock上调用。
您尝试创建如下模拟是正确的:
@Mock
private HttpSession session;
然而,您忽略了实际进行创建的调用:
MockitoAnnotations.initMocks(this);
将上面的行添加到测试中,最好是在设置方法中,when()
调用应该可以工作。