unable to put spy on HttpSession / Mockito
java, mockito, unit-testing
Solution
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());
Problem
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`.