Jmock如何与HttpSession和HttpServletRequest一起使用
题
我是jmock的新手并试图模仿HttpSession。我得到了:
java.lang.AssertionError:意外调用:httpServletRequest.getSession() 没有指定的期望:你...... - 忘记用基数条款开始期待? - 调用模拟方法来指定期望的参数?
测试方法:
@Test
public void testDoAuthorization(){
final HttpServletRequest request = context.mock(HttpServletRequest.class);
final HttpSession session = request.getSession();
context.checking(new Expectations(){{
one(request).getSession(true); will(returnValue(session));
}});
assertTrue(dwnLoadCel.doAuthorization(session));
}
我做了一些搜索,但我还不清楚这是怎么做到的。感觉就像我错过了一些小块。任何有这方面经验的人都可以指出我正确的方向。 感谢
解决方案
您无需模拟请求对象。由于您正在测试的方法( dwnLoadCel.doAuthorization()
)仅依赖于 HttpSession
对象,因此您应该模拟它。所以你的代码看起来像这样:
public void testDoAuthorization(){
final HttpSession session = context.mock(HttpSession.class);
context.checking(new Expectations(){{
// ???
}});
assertTrue(dwnLoadCel.doAuthorization(session));
}
问题变成:您希望SUT与会话对象实际做什么?您需要在期望中表达对 session
的调用及其相应的返回值,这些返回值应该导致 doAuthorization
返回 true
。
其他提示
我认为您需要告诉JMock上下文在实际进行调用之前,您希望调用该方法的次数。
final HttpServletRequest request = context.mock(HttpServletRequest.class);
context.checking(new Expectations(){{
one(request).getSession(true); will(returnValue(session));
}});
final HttpSession session = request.getSession();
我对JMock并不是很熟悉,但你真的关心你的 dwnLoadCel
单元测试模拟对象中某些方法的调用次数吗?或者您只是尝试在没有实际会话的情况下测试依赖于HttpSession的类?如果是后者而不是我认为JMock对你来说太过分了。
您可能希望自己创建一个实现 HttpSession
接口的类,仅用于单元测试(存根),然后运行测试,或者您应该查看 dwnLoadCel
并确定确实是否需要引用HttpSession,或者它是否只需要HttpSession中的某些属性。重构 dwnLoadCel
只取决于它实际需要什么(一个 Map
或Session对象中的某个参数值) - 这将使你的单元测试更容易(依赖于servlet容器再见。
我认为你的类中已经有一定程度的依赖注入,但你可能依赖于太广泛的对象。 Google测试博客已很多 优秀 文章最近您可能会觉得有用(我肯定有)。