问题描述
我想在 Httpsession
上进行部分模拟,但为此我需要监视它而不是模拟它,而且如果没有已经模拟的请求对象,我就无法获得一个接口.
I want partial mocking on Httpsession
but for that i need to spy it instead of mocking it , and it's a interface I can't get without request object which is already mocked.
请帮忙.
换句话说,如果没有 HttpServletRequest
对象,如何获得 HttpSession
的对象.
In another word , how can I get a object of HttpSession
without HttpServletRequest
object.
更多细节::
有一个我想测试的 servlet,servlet 有会话并将loginBean"(包含登录的用户相关信息)放入会话中,我已经模拟并且工作正常,现在在 GUI 级别,有 2 个选项卡, DetailSet1 , detailsSet2 ,当你输入 DetailSet1 的数据时,它会保存在 session 中并执行一些业务逻辑,现在谈到 DetailsSet2 ,你已经在 session 中有 DetailSet1 ,所以它得到了它需要的一切,数据保存在 DB 中.不,很明显我必须模拟 HttpSession
因为我从容器外部运行单元案例,但是如果我也模拟这些数据,那么存储的数据也在 Httpsession
中,它违背了测试的目的.回到我开始的内容,我需要 Httpsession
对象来为我模拟的内容返回模拟数据,并且在其他情况下它应该像任何普通的 HttpSession
对象一样.就像,如果我做 session.setAttribute("name","Vivek) ,那么 session.getAttribute("name")
应该 return "Vivek"
之后,但在模拟对象的情况下它返回 null
为什么?因为我没有模拟 getAttribute("name")
的行为.如果我仍然无法做到,我真的很抱歉任何人都明白我的要求.
There is a servlet I want to test , servlet have session and puts "loginBean" (which contain loged in user related info) inside session, which I have mocked already and working fine , now IN GUI level , there are 2 tab , DetailSet1 , detailsSet2 , when you enter data of DetailSet1 , it get saved in session and also does some business logic , now it comes to DetailsSet2 , you already have DetailSet1 in session , so it got all it needs , data is saved in DB. No it's obvious I have to mock HttpSession
because I am running unit cases from outside the container , but data which gets stored is also in Httpsession
, if I mock those as well , it defeats the purpose of testing. back to what I started with , I need Httpsession
object to return mocked data for what I have it mocked for and it is suppose to act like any normal HttpSession
object for other cases. Like , if I do session.setAttribute("name","Vivek) , then session.getAttribute("name")
should return "Vivek"
after that , but in case of mocked object it return null
why? because I haven't mocked behaviour for getAttribute("name")
. I am really sorry if I am still can't make anyone understand what I am asking for.
简而言之,对 HttpSession
进行部分模拟.
In simple word Partial mocking on HttpSession
.
推荐答案
好的,我明白了.您实际上无法访问真正的会话对象,也不会进行任何间谍活动.你需要你的自制模拟(假的):
ok I get it. you don't really have access to the real session object and you won't do any spy. you need your home-made mock (fake):
public class MockHttpSession implements HttpSession {
Map<String, Object> map = new HashMap<>();
@Override
public Object getAttribute(String name) {
return map.get(name);
}
@Override
public void setAttribute(String name, Object value) {
map.put(name, value);
}
// implement rest of the methods you will use
然后在您的测试中,您将拥有:
and then in your test you'll have:
when(request.getSession()).thenReturn(new MockHttpSession());
这篇关于无法监视 HttpSession/Mockito的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!