HttpSession
is an interface, so you'll need to either write your own implementation of it, or mock it. I would recommend mocking it with Mockito, then stubbing getAttribute
and setAttribute
to delegate to a HashMap
, or some other suitable structure.
So in your test class, you'll have fields for
- your mocked
HttpSession
, - a real
HashMap<String,Object>
and you'll use Answer<Object>
objects for each of getAttribute
and setAttribute
. Each Answer
will just delegate the call off to the HashMap
.
You could set all this up either in a @Before
method, or in a @Test
method like this.
@Mock private HttpSession mockHttpSession;
Map<String,Object> attributes = new HashMap<String,Object>();
@Test
public void theTestMethod() {
Mockito.doAnswer(new Answer<Object>(){
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String key = (String) invocation.getArguments()[0];
return attributes.get(key);
}
}).when(mockHttpSession).getAttribute(anyString());
Mockito.doAnswer(new Answer<Object>(){
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String key = (String) invocation.getArguments()[0];
Object value = invocation.getArguments()[1];
attributes.put(key, value);
return null;
}
}).when(mockHttpSession).setAttribute(anyString(), any());