Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create session in Spring Junit

I have such layers:

Spring Controller -> Services layer -> Dao Layer (JPA).

I want to write test cases of services and controller. In the other Junit will invoke controller, controller will invoke services, service layer gets database information and etc..

In this case I do not want mocking, I want just to write junit test case (I must invoke service and service must get real data from database).

I have only one problem, service layer get's user id from session. I get session with autowired annotation. How can I create fake session during test cases?

p.s I think mock is not for me... because I do not wont to mock my service, I want to create real invoke of controller with real db data...

like image 221
grep Avatar asked Oct 19 '25 02:10

grep


1 Answers

We can do with mock. Here is sample of code.

private MockMvc mockMvc;

        @Autowired
        private FilterChainProxy springSecurityFilterChain;

        @Autowired
        private WebApplicationContext wac;

        protected MockHttpSession session;

        protected MockHttpServletRequest request;

        @Before
        public void setup() {
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilters(this.springSecurityFilterChain).build();
        }

        @Test
        void test(){
        // I log in and then returns session 
        HttpSession session = mockMvc.perform(post("/j_spring_security_check").param("NAME", user).param("PASSWORD", pass))
                    .andDo(print()).andExpect(status().isMovedTemporarily()).andReturn().getRequest().getSession();
        }

Also we can do with this way, you can just to call startSession() method, and there will be "current" session returned.

protected void startSession() {
        session = new MockHttpSession();
    }

    protected void endSession() {
        session.clearAttributes();
        session = null;
    }

    // we can create request too, just simple way
    protected void startRequest() {
        request = new MockHttpServletRequest();
        request.setSession(session);
        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
    }
like image 52
grep Avatar answered Oct 21 '25 16:10

grep