2

I inject the HttpSession into my controller with @Autowired:

@RestController
public class MyController {

    @Autowired
    private HttpSession httpSession;

    @GetMapping("hello")
    public String getHello() {
        return "hello " + httpSession.getId();
    }

}

How can I mock the session in a @WebMvcTest annotated test?

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private HttpSession session;

    @Test
    public void testGetHello() throws Exception {
        when(session.getId()).thenReturn("sessionId");
        mvc.perform(get("/hello"))
            .andExpect(status().isOk())
            .andExpect(content().string("hello sessionId"));
    }

}

This solution throws exception: No qualifying bean of type 'javax.servlet.http.HttpSession' available

nagy.zsolt.hun
  • 6,292
  • 12
  • 56
  • 95
  • Possible duplicate of [Mocking HttpSession using Mockito](https://stackoverflow.com/questions/30848865/mocking-httpsession-using-mockito) – Lemmy Nov 02 '19 at 21:16
  • Furthermore, I would suggest using the [MockHttpSession](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/mock/web/MockHttpSession.html) instead of mocking a HttpSession – Michiel Nov 03 '19 at 09:12

0 Answers0