Monday, 7 July 2014

Adding custom implementations to mock objects

It shows how to add customs implementations to a mocked class using Mockito framework, this particularly example shows implementations for setAttribute and getAttribute methods of the class javax.serlvet.HttpSession
   
    doAnswer(new Answer<Object>() {
      @Override
      public Object answer(InvocationOnMock invocation) throws Throwable {
        return sessionHolder.put((String) invocation.getArguments()[0],
            (String) invocation.getArguments()[1]);
      }
    }).when(session).setAttribute(anyString(), anyObject());
    when(session.getAttribute(anyString())).then(new Answer<String>() {
      @Override
      public String answer(InvocationOnMock invocation) throws Throwable {
        return sessionHolder.get(invocation.getArguments()[0]);
      }
    });