Failed to install spy on HttpSession / Mockito

I want to partially mock Httpsession, but for this I need to spy on him, and not mock him, and this is an interface that I can not get without a request object, which is already ridiculed.

Please, help.

In another word, how can I get an object Httpsessionwithout an object HttpServletRequest.

DETAILED INFORMATION::

There is a servlet that I want to check, the servlet has a session and places a "loginBean" (which contains information related to the user) inside a session that I already mocked and worked fine, now at the GUI level there are 2 tabs, DetailSet1, detailsSet2, when you enter DetailSet1 data, it is saved in the session, and also performs some business logic, now it comes to DetailSet2, you already have DetailSet1 in the session, so it got everything you need, the data is saved in the database. It is not obvious that I have to scoff at Httpsession, because I run single cases from outside the container, but the data that is stored is also in Httpsession, if I simulate them too, it defeats the purpose of testing. back to where I started, I need an objectHttpsessionto return the mocked data for what I ridiculed him for, and it should act like any ordinary object Httpsessionfor other cases. For example, if I execute session.setAttribute ("name", "Vivek"), then I session.getAttribute("name")should return "Vivek"after that, but in case of a mocking object, it returns nullwhy? Because I did not make fun of the behavior for getAttribute("name")I am very sorry if I still can not make someone understand what I ask.

In a simple word Partial mockery of Httpsession.

+4
source share
2 answers

OK, I get it. you really don’t have access to the real session object, and you won’t do the spy. you need your home layout (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

:

when(request.getSession()).thenReturn(new MockHttpSession());
+5

HttpSession ( FakeHttpSession , Martin Fowlers bliki).

Mockito.

+3

Source: https://habr.com/ru/post/1533864/


All Articles