unable to put spy on HttpSession / Mockito

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

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.

please help.

In another word , how can I get a object of HttpSession without HttpServletRequest object.

MORE DETAIL::

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.

In simple word Partial mocking on HttpSession.

回答1:

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()); 


回答2:

Just implement the interface HttpSession yourself (I'd name it FakeHttpSession, based on the names proposed in Martin Fowlers bliki).

Then you create an instance and spy on it using Mockito.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!